elementui Select 选择器 结合tree 实现TreeSelect
个人实现记录
- 效果 可以设置默认要展开和勾选的状态
- 点击select里的标签 关闭树形图对应的取消勾选效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/89c1cb327ebed6ec02f9bd59ffdcd8ee.gif)
html
<el-select v-model="value1" multiple placeholder="请选择" @change="changeData">
<el-option style="height:auto" :value="SelectedArray">
<el-tree
:data="dataList"
show-checkbox
node-key="id"
ref="tree"
:check-strictly="true"
highlight-current
:props="defaultProps"
@check="checkClick"
:default-expanded-keys="setkey"
:default-expand-all="false"
>
</el-tree>
</el-option>
</el-select>
- default-expand-all 是否默认展开所有节点
- default-expanded-keys 默认展开的节点的 key 的数组
- check 当复选框被点击的时候触发
-check-strictly父子节点不相互关联 - highlight-current 是否高亮当前选中节点,默认值是 false。
代码部分
data () {
return {
setkey: [1],
dateList: [],
SelectedArray: [12, 13],
dataList: [
{
id: 1,
name: '总公司',
parent_id: null,
parent_name: null,
has_children: true,
children: [
{
id: 2,
name: '1xxxx部门',
parent_id: 1,
parent_name: '总公司',
has_children: true,
children: [
{
id: 12,
name: 'x1x项目',
parent_id: 1,
parent_name: '1xxxx部门',
has_children: false,
children: []
},
{
id: 13,
name: 'x22222x项目',
parent_id: 2,
parent_name: '1xxxx部门',
has_children: true,
children: [
{
id: 19,
name: 'xxx',
parent_id: 13,
parent_name: 'x22222x项目',
has_children: false,
children: []
}
]
}
]
},
{
id: 15,
name: '管理办公室',
parent_id: 1,
parent_name: '总公司',
has_children: false,
children: []
},
{
id: 16,
name: '技术中心',
parent_id: 1,
parent_name: '总公司',
has_children: false,
children: []
}
]
}
],
value1: [],
defaultProps: {
children: 'children',
label: 'name'
}
}
},
<script>
methods: {
async getTreeData () {
try {
const {
data: { data }
} = await this.$http.get('http://localhost:8848/treeData')
console.log(data)
this.dataList = data.data_list
console.log(this.dataList)
} catch (error) {
console.log(error)
}
},
changeData (e) {
console.log('选中改变的值', e, this.dateList)
const setkey = []
for (let index = 0; index < this.dateList.length; index++) {
for (let index1 = 0; index1 < e.length; index1++) {
if (this.dateList[index].name === e[index1]) {
setkey.push(this.dateList[index].id)
}
}
}
console.log(setkey)
this.setkey = setkey
this.$refs.tree.setCheckedKeys(this.setkey)
},
checkClick (checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) {
const res = this.$refs.tree.getCheckedNodes(false, true)
console.log('点击树形图获取当前选中的节点', res)
this.dateList = res
const labelArr = []
const valueArr = []
res.forEach((element, index) => {
labelArr.push(element.name)
valueArr.push(element.id)
})
this.value1 = labelArr
this.SelectedArray = valueArr
console.log(this.value1, this.SelectedArray)
}
},
created () {
},
mounted () {
this.$refs.tree.setCheckedKeys(this.setkey)
}
}
</script>