<template>
<div class="eltree">
<span
>子级选中关联父级全部选中,父级取消选中子级全部取消选中,父级选中子级不选中</span
>
<el-tree
ref="tree"
:data="treeData"
show-checkbox
node-key="id"
:props="defaultProps"
:check-strictly="true"
:default-checked-keys="selectTreeArr"
@check="checkChange"
>
</el-tree>
</div>
</template>
<script>
export default {
name: "eltree",
data() {
return {
treeData: [
{
id: 1,
label: "一级 1",
children: [
{
id: 4,
label: "二级 1-1",
children: [
{
id: 9,
label: "三级 1-1-1",
},
{
id: 10,
label: "三级 1-1-2",
},
],
},
],
},
{
id: 2,
label: "一级 2",
children: [
{
id: 5,
label: "二级 2-1",
},
{
id: 6,
label: "二级 2-2",
},
],
},
{
id: 3,
label: "一级 3",
children: [
{
id: 7,
label: "二级 3-1",
},
{
id: 8,
label: "二级 3-2",
},
],
},
],
defaultProps: {
children: 'children',
label: 'label'
},
selectTreeArr: [], //选中的
};
},
methods: {
checkChange(data) {
const node = this.$refs.tree.getNode(data.id);
this.setNode(node);
},
setNode(node) {
console.log(node, "node");
if (node.checked) {
//如果当前是选中checkbox,则递归设置父节点和父父节点++选中
this.setParentNode(node);
} else {
//当前是取消选中,将所有子节点都取消选中
this.setChildenNode(node);
}
},
setParentNode(node) {
if (node.parent) {
for (const key in node) {
if (key === "parent") {
node[key].checked = true;
this.setParentNode(node[key]);
}
}
}
},
setChildenNode(node) {
let len = node.childNodes.length;
for (let i = 0; i < len; i++) {
node.childNodes[i].checked = false;
this.setChildenNode(node.childNodes[i]);
}
},
},
};
</script>
详情请见git地址
版权声明:本文为qq_40011214原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。