element-ui使用select組件和tree組件實(shí)現(xiàn)下拉樹形選擇器

template部分

<el-select class="select">
    <el-option class="option">
        <el-tree class="tree"></el-tree>
    </el-option>
</el-select>

一個(gè)三級(jí)嵌套就可以搞定

css部分

    .option {
        height: auto;
        line-height: 1;
        padding: 0;
        background-color: #fff;
    }
    .tree {
        padding: 4px 20px;
        font-weight: 400;
    }

網(wǎng)上的辦法大多都是直接在option上寫,給option加一個(gè)高度,然后overflow: auto,這樣會(huì)有問題, 因?yàn)閟elect本身使用的是element-ui自己的滾動(dòng)條組件, max-height為274px,一旦option設(shè)置高度過大,會(huì)出現(xiàn)雙重滾動(dòng)條,而且原生滾動(dòng)條真的有點(diǎn)丑,其實(shí)這里只需要給option加一個(gè)height: auto,就可以使用select自帶的滾動(dòng)條,不需要單獨(dú)再加其他滾動(dòng)。

發(fā)現(xiàn)兩個(gè)問題

  1. 當(dāng)樹展開的時(shí)候,動(dòng)畫不流暢,會(huì)抖動(dòng)一下。分析了一下已有的css,發(fā)現(xiàn)是因?yàn)閛ption本身設(shè)置了 line-height: 34px;而樹形里沒有設(shè)置line-height,設(shè)置的是高度為26px。這里直接把option的line-height改為1,果然動(dòng)畫流暢了,舒服了。
  2. 當(dāng)option被選中時(shí),樹節(jié)點(diǎn)所有的文字都會(huì)加粗,隨便設(shè)置一個(gè)font-weight: 400就行。

js部分

要解決幾點(diǎn)

  1. 點(diǎn)擊樹時(shí),下拉框不會(huì)自動(dòng)隱藏,一看文檔也沒有控制下拉框顯示隱藏的屬性,然后在select組件源碼中找到了visible,控制下拉框顯示隱藏
    點(diǎn)擊樹時(shí)設(shè)置this.$refs.select.visible = false

  2. 數(shù)據(jù)回顯,通過tree的setCurrentKey方法設(shè)置當(dāng)前高亮的節(jié)點(diǎn),通過getNode方法獲取當(dāng)前id對(duì)應(yīng)的node,拿到對(duì)應(yīng)的label

  3. 不管選沒選擇內(nèi)容,打開下拉框的時(shí)候,滾動(dòng)條永遠(yuǎn)在最底部,實(shí)在是太難受了。而一想到是不是不能借助select的滾動(dòng),而要給option設(shè)置滾動(dòng)時(shí)就更難受了。但是給option設(shè)置滾動(dòng)后,發(fā)現(xiàn)滾動(dòng)條永遠(yuǎn)在最頂部,舒服了,也有問題。
    突然想到,一個(gè)正常不魔改的select組件,選中哪個(gè)option時(shí),打開下拉框總能定位到那個(gè)選中的,這肯定是select組件內(nèi)部有個(gè)方法做的,偷過來用就行。然后就找到了這個(gè)

      scrollToOption(option) {
        const target = Array.isArray(option) && option[0] ? option[0].$el : option.$el;
        if (this.$refs.popper && target) {
          const menu = this.$refs.popper.$el.querySelector('.el-select-dropdown__wrap');
          scrollIntoView(menu, target);
        }
        this.$refs.scrollbar && this.$refs.scrollbar.handleScroll();
      },

scrollToOption?拿來吧你

很明顯,要傳入一個(gè)option對(duì)象,而option的$el屬性是一個(gè)dom,則表現(xiàn)形式就是一個(gè)Vue的實(shí)例,我這邊直接用querySelector獲取一個(gè)dom, 傳入{ $el: dom }也能用。再然后就是找這個(gè)dom,發(fā)現(xiàn)當(dāng)樹某一節(jié)點(diǎn)被點(diǎn)擊時(shí),其class會(huì)多一個(gè)is-current,那么就可以這樣寫:

let selectDom = document.querySelector('.is-current')
this.$refs.select.scrollToOption({$el: selectDom})

ps: 只針對(duì)單選做的,多選還需按照情況改。

組件全部代碼

<template>
    <el-select ref="select" :value="value" placeholder="請(qǐng)選擇" size="mini" @visible-change="visibleChange" clearable style="width: 100%;" @clear="clear">
        <el-option ref="option" class="option" :value="optionData.id" :label="optionData.name">
            <el-tree ref="tree" class="tree" :node-key="nodeKey" :data="data" :props="props" :default-expanded-keys='[value]'
                highlight-current :expand-on-click-node="false" @node-click="handleNodeClick"></el-tree>
        </el-option>
    </el-select>

</template>

<script>
    export default {
        name: 'TreeSelect',
        props: {
            // v-model綁定
            value: {
                type: [String, Number],
                default: ''
            },
            // 樹形的數(shù)據(jù)
            data: {
                type: Array,
                default: function() {
                    return []
                }
            },
            // 每個(gè)樹節(jié)點(diǎn)用來作為唯一標(biāo)識(shí)的屬性
            nodeKey: {
                type: [String, Number],
                default: 'id'
            },
            // tree的props配置
            props: {
                type: Object,
                default: function() {
                    return {
                        label: 'label',
                        children: 'children'
                    }
                }
            }
        },
        data() {
            return {
                optionData: {
                    id: '',
                    name: ''
                }
            }
        },
        watch: {
            'value': function(val) {
                if(!this.isEmpty(this.data)){
                    this.init(val)
                }
            },
            'data': function(val) {
                if(!this.isEmpty(val)){
                    this.init(this.value)
                }
            }
        },
        mounted() {
            if(!this.isEmpty(this.data)){
                this.init(this.value)
            }
        },
        methods: {
            // 是否為空
            isEmpty(val) {
                for (let key in val) {
                  return false
                }
                return true
            },
            handleNodeClick(data) {
                let label = this.props.label || 'name'
                this.$emit('input', data[this.nodeKey])
                this.optionData.id = data[this.nodeKey]
                this.optionData.name = data[label]
                this.$refs.select.visible = false
            },
            init(val) {
                if (val) {
                    this.$nextTick(() => {
                        let label = this.props.label || 'name'
                        this.$refs.tree.setCurrentKey(val)
                        let node = this.$refs.tree.getNode(val)
                        this.optionData.id = val
                        this.optionData.name = node.label
                    })
                } else{
                    this.$refs.tree.setCurrentKey(null)
                }
            },
            visibleChange(e) {
                if(e) {
                    let selectDom = document.querySelector('.is-current')
                    setTimeout(() => {
                        this.$refs.select.scrollToOption({$el: selectDom})
                    },0)
                }
            },
            clear() {
                this.$emit('input', '')
            }
        }
    }
</script>

<style lang="scss" scoped>
    .option {
        height: auto;
        line-height: 1;
        padding: 0;
        background-color: #fff;
    }

    .tree {
        padding: 4px 20px;
        font-weight: 400;
    }
</style>

在組件中的使用

<template>
    <div class="container">
        <cy-tree-select v-model="value" :data="list" style="width: 240px;"></cy-tree-select>
    </div>
</template>

<script>
export default {
    data() {
        return {
            list: [{
                label: '系統(tǒng)',
                id: 1,
                children: [
                    { label: '用戶', id: 2 },
                    { label: '用戶組', id: 3 },
                    { label: '角色', id: 4 },
                    { label: '菜單', id: 5 },
                    { label: '組織架構(gòu)', id: 6 }
                ]
            },
            {
                label: '商品',
                id: 7,
                children: [
                    { label: '列表', id: 8 },
                    { label: '添加', id: 9 },
                    { label: '修改', id: 10 },
                    { label: '刪除', id: 11 },
                    { label: '商品分類', id: 12 },
                    { label: '分類修改', id: 13 }
                ]
            }],
            value: 1
        }
    }
}
</script>

效果圖

chrome-capture-2022-2-5 (1).gif

代碼放在gitgub上了,地址:vue-cy-admin

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容