Vue+Element UI 整合下拉目录树(popover+ tree+input)

一、演示效果

 

二、完整代码

<template>
    <el-popover
        placement="bottom-start"
        title=""
        width="300"
        v-model="showTree"
        popper-class="el-popover-tree"
        trigger="click"
        content="">
        <el-input class="dataset-tree-picker"
            v-model="showValue"
            placeholder="请选择"
            clearable
            @focus="handleFocus"
            @blur="handleBlur"
            @change="handleChange"
            :suffix-icon="showIcon"
            slot="reference" />
        <div class="dataset-tree-picker__content">
            <el-tree :data="tree"
                ref="tree"
                :node-key="props.key"
                v-loading="loading"
                :props="props"
                :default-expanded-keys="expandedKeys"
                :default-checked-keys="checkedKeys"
                :filter-node-method="filterNode"
                @node-click="handleNodeClick"></el-tree>
        </div>
    </el-popover>
</template>

<script>
export default {
    name: 'info-config-tree',
    data () {
        return {
            init: false,
            showTree: false, // 显示隐藏目录树
            canFilter: false, // 目录树是否支持搜索
            loading: false, // 当前选择的节点
            expandedKeys: [], // 默认展开的节点的key的数组
            checkedKeys: [], // 默认勾选的节点的key的数组
            selected: {},
            showValue: '', // input框显示的中文值
            // 目录树配置项
            props: {
                key: 'Id',
                label: 'Label',
                children: 'ChildNodes',
                isLeaf: 'HasChildren'
            },
            // 目录树数据
            tree: [
                {
                    Enable: false,
                    HasChildren: true,
                    Id: '44',
                    NodeId: 448,
                    OrderNum: 1,
                    Parent: true,
                    Label: '广东省',
                    ChildNodes: [
                        {
                            Enable: false,
                            HasChildren: true,
                            Id: '4401',
                            NodeId: 449,
                            OrderNum: 1,
                            Parent: true,
                            ParentId: '44',
                            ParentLabel: '广东省',
                            Label: '广州市',
                            ChildNodes: [
                                {
                                    Enable: false,
                                    HasChildren: false,
                                    Id: '440103',
                                    NodeId: 450,
                                    OrderNum: 1,
                                    Parent: true,
                                    ParentId: '4401',
                                    ParentLabel: '广州市',
                                    Label: '荔湾区',
                                    ChildNodes: []
                                },
                                {
                                    Enable: false,
                                    HasChildren: false,
                                    Id: '440104',
                                    NodeId: 479,
                                    OrderNum: 1,
                                    Parent: true,
                                    ParentId: '4401',
                                    ParentLabel: '广州市',
                                    Label: '越秀区',
                                    ChildNodes: []
                                }
                            ]
                        },
                        {
                            Enable: false,
                            HasChildren: false,
                            Id: '4403',
                            NodeId: 1017,
                            OrderNum: 1,
                            Parent: true,
                            ParentId: '44',
                            ParentLabel: '广东省',
                            Label: '深圳市',
                            ChildNodes: []
                        }
                    ]
                }
            ]
        };
    },
    computed: {
        // input尾部显示上下箭头icon
        showIcon () {
            if (this.showValue !== '') {
                return '';
            } else {
                return this.showTree ? 'el-icon-arrow-up' : 'el-icon-arrow-down';
            }
        }
    },
    watch: {
        // 监听input框值变化,如果当前状态是搜索,则调用目录树搜索方法
        showValue (val) {
            if (!this.canFilter) {
                return;
            }
            this.$refs.tree.filter(val);
        }
    },
    created () {
        this.getTreeList();
    },
    methods: {
        // 通过key设置某个节点的当前选中状态
        async setCurrentKey (id) {
            await this.getTreeList();
            this.$nextTick(() => {
                const node = this.$refs.tree.getNode(id);
                if (node) {
                    this.expandedKeys = this.getDefaultExpandedKeys(this.tree, id);
                    this.$refs.tree.setCurrentKey(id);
                    this.selected = node.data;
                    this.showValue = this.selected[this.props.label];
                    return this.selected;
                }
            });
        },

        // 默认展开
        getDefaultExpandedKeys (tree, id, keys = []) {
            for (let i = 0, len = tree.length; i < len; i++) {
                const item = tree[i];
                if (item[this.props.key] === id) {
                    keys.push(item[this.props.key]);
                    return keys;
                }
                if (item[this.props.children] && item[this.props.children].length) {
                    const temp = this.getDefaultExpandedKeys(item[this.props.children], id, keys);
                    temp.length && (keys = keys.concat(temp));
                }
            }
            return keys;
        },

        // input框值改变
        handleChange (val) {
            this.$emit('change', '');
        },

        // input聚焦
        handleFocus () {
            this.showValue = '';
            this.canFilter = true;
        },

        // input失去焦点
        handleBlur () {
            this.canFilter = false;
            this.showValue = this.selected[this.props.label];
        },

        // 对树节点进行筛选时执行的方法
        filterNode (value, data) {
            if (!value) return true;
            return (data[this.props.label] || '').toLowerCase().indexOf((value || '').toLowerCase()) !== -1;
        },

        // 节点点击事件
        handleNodeClick (data) {
            if (data[this.props.key]) {
                this.selected = data;
                this.showValue = data[this.props.label];
                this.$emit('change', data[this.props.key]); // 发送给父组件
                this.showTree = false;
            }
        },

        // 默认展开和选中第一项
        setExpandDefault (tree = this.tree) {
            let firstItem = tree.find(d => {
                return d && (d[this.props.children] || []).length;
            });
            if (!firstItem) {
                firstItem = tree[0];
            }
            if (!firstItem) return;
            this.expandedKeys.push(firstItem[this.props.key]);
            this.checkedKeys.push(firstItem[this.props.key]);
            this.handleNodeClick(firstItem);
        },

        // 接口获取数据源树
        async getTreeList () {
            try {
                // 接口获取 当前为了测试在data写死了目录树数据
                // if (this.init) {
                //     return;
                // }
                // this.loading = true;
                // const result = await this.$api.getTreeList();
                // this.tree = result.Data;
                if (!this.init) {
                    this.$nextTick(() => {
                        this.expandedKeys = [];
                        this.checkedKeys = [];
                        this.setExpandDefault();
                    });
                }
                this.init = true;
            } catch (error) {
                console.log(error);
            } finally {
                this.loading = false;
            }
        }
    }
};
</script>

<style lang="scss">
.dataset-tree-picker {
    &__content {
        max-height: 500px;
        overflow: auto;

        .el-tree {
            &-node {
                &.is-current {
                    & > .el-tree-node__content {
                        background: $--color-primary-light-1;
                    }
                }
            }
        }
    }
}
</style>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Vue是一个流行的前端JavaScript框架,而Element UI是一个基于Vue的桌面端UI组件库。Vue + Element UI可以帮助开发者快速构建具有美观、交互性和响应式的Web应用程序。 下面是一个Vue + Element UI的示例,实现了一个简单的表格和一个表单。在示例中,我们首先安装VueElement UI,然后创建Vue实例,并在其中引入Element UI组件,最后将Vue实例挂载到HTML页面上。 引用:以下是Vue + Element UI的示例[^1]: ```HTML <!DOCTYPE html> <html> <head> <title>Vue + Element UI</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script> </head> <body> <div id="app"> <el-table :data="tableData" style="width: 100%"> <el-table-column prop="name" label="姓名"></el-table-column> <el-table-column prop="age" label="年龄"></el-table-column> <el-table-column prop="gender" label="性别"></el-table-column> </el-table> <el-form :model="form" label-width="80px"> <el-form-item label="姓名"> <el-input v-model="form.name"></el-input> </el-form-item> <el-form-item label="年龄"> <el-input-number v-model="form.age"></el-input-number> </el-form-item> <el-form-item label="性别"> <el-radio-group v-model="form.gender"> <el-radio label="male">男性</el-radio> <el-radio label="female">女性</el-radio> </el-radio-group> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form-item> </el-form> </div> <script> new Vue({ el: '#app', data: { tableData: [{ name: '张三', age: 18, gender: 'male' }, { name: '李四', age: 22, gender: 'female' }], form: { name: '', age: '', gender: '' } }, methods: { submitForm() { alert(JSON.stringify(this.form)); } } }) </script> </body> </html> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Demi

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值