el-select实现下拉树
// template
<el-select
ref="el-select-ref"
v-model="form.pid"
@change="selectChange"
@visible-change="showSelectTree"
@clear="clearSelectTree"
>
<!-- 添加一个option选项 使用hidden隐藏 value是下拉选中的值,label是显示的名称 -->
<el-option key="id" hidden :value="form.pid" :label="form.pidName" />
<el-tree
ref="el-select-tree"
:data="treeData"
:props="defaultProps"
node-key="menuId"
highlight-current
default-expand-all
:expand-on-click-node="false"
@node-click="handleNodeClick"
/>
</el-select>
// script
<script>
export default {
data() {
return {
tableData: [{
"menuId": 8,
"pid": 0,
"name": "系统管理",
"children": [
{
"menuId": 3,
"pid": 8,
"name": "用户管理",
"children": [
{ "menuId": 4, "pid": 3, "name": "用户列表", "children": [] },
{ "menuId": 9, "pid": 3, "name": "用户添加", "children": [] },
{ "menuId": 10, "pid": 3, "name": "用户编辑", "children": [] },
{ "menuId": 11, "pid": 3, "name": "用户删除", "children": [] }
]
},
{
"menuId": 12,
"pid": 8,
"name": "角色管理",
"children": [
{ "menuId": 17, "pid": 12, "name": "角色列表", "children": [] },
{ "menuId": 18, "pid": 12, "name": "角添加色", "children": [] },
{ "menuId": 19, "pid": 12, "name": "编辑角色", "children": [] },
{ "menuId": 20, "pid": 12, "name": "删除角色", "children": [] }
]
},
{ "menuId": 7, "pid": 8, "name": "字典管理", "children": [] },
{
"menuId": 2,
"pid": 8,
"name": "菜单管理",
"children": [
{ "menuId": 13, "pid": 2, "name": "菜单列表", "children": [] },
{ "menuId": 14, "pid": 2, "name": "添加菜单", "children": [] },
{ "menuId": 15, "pid": 2, "name": "编辑菜单", "children": [] },
{ "menuId": 16, "pid": 2, "name": "删除菜单", "children": [] }
]
},
{ "menuId": 21, "pid": 8, "name": "聚合图床", "icon": "tree", "children": [] }
]
}],
form: {
pid: 0,
pidName: '根目录'
},
defaultProps: {
children: 'children',
label: 'name'
}
}
},
methods: {
showSelectTree(bool) { // el-select下拉框显示或隐藏触发
// 设置当前绑定的tree节点高亮
if (bool) this.$refs['el-select-tree'].setCurrentKey(this.form.pid)
},
handleNodeClick(data, node, nodeRef) { // 点击tree下拉节点
// console.log(data, node, nodeRef)
this.form.pid = data.menuId // 设置el-select绑定的value
this.form.pidName = data.name // 设置el-select绑定的lable
this.$refs['el-select-ref'].handleClose() // 关闭el-select下拉框
// this.$set(this.form, 'pid', data.menuId)
},
clearSelectTree() { // 清空el-select触发 需要给el-select添加 clearable属性
this.form.pidName = ''
this.$refs['el-select-tree'].setCurrentKey(null)
},
}
}
</script>
实现效果展示
如需封装成组件,可以自行进行封装,这里就不再进行组件封装
评论 (0)