<template>
<div>
<el-tree
:data="dataTree"
show-checkbox
node-key="id"
@check="handleCheckChange"
>
</el-tree>
</div>
</template>
<script>
export default {
data() {
return {
data: [
{
id: 1,
label: '美食',
parentId: 0,
},
{
id: 2,
label: '鱼香肉丝',
parentId: 1,
},
{
id: 3,
label: '干锅牛蛙',
parentId: 1,
},
{
id: 4,
label: '饮料',
parentId: 0,
},
{
id: 5,
label: '可乐',
parentId: 4,
},
{
id: 6,
label: '雪碧',
parentId: 4,
},
{
id: 7,
label: '奶茶',
parentId: 4,
},
{
id: 8,
label: '珍珠奶茶',
parentId: 7,
},
{
id: 9,
label: '丝袜奶茶',
parentId: 7,
},
],
dataTree: [],
}
},
methods: {
formatDataTree() {
const parents = this.data.filter(p => p.parentId === 0) //顶集
const children = this.data.filter(c => c.parentId !== 0) //子集
console.log('父:', parents, '子:', children)
this.dataToTree(parents, children)
},
dataToTree(parent, children) {
parent.map(p => {
children.map((c, i) => {
if (c.parentId == p.id) {
const _children = JSON.parse(JSON.stringify(children))
_children.splice(i, 1)
this.dataToTree([c], _children) //递归:处理子集的子集
if (p.children) {
p.children.push(c)
} else {
p.children = [c]
}
}
})
})
this.dataTree = parent
},
handleCheckChange(checkedNodes, checkedKeys) {
console.log(
'传递给 data 属性的数组中该节点所对应的对象',
checkedNodes,
'树目前的选中状态对象',
checkedKeys
)
},
},
created() {
this.formatDataTree()
console.log('树形结构数据', this.dataTree)
},
}
</script>
<style lang="scss" scoped></style>
如上的代码实现了:
1.从后端返回的扁平化数组,前端通过递归的方式,将数组通过parentId绑定父集,实现树形结构化
2.通过勾选树形结构的复选框,获取勾选节点的key,这里的key我选择了id
至此,我们就完成了数组转成树形结构,并且勾选树形结构对应的节点,可以获取所有选中的id数组
注意点:
//el-tree的方法:
@check="handleCheckChange"