The tree structure method can refer to the <el-tree></el-tree> method of elementUI official website. I have already encapsulated the tree method here, this part is omitted! The purpose here is to select how the parent class traverses the method of the child class.
Encapsulated My-tree.vue
略!!!
<el-tree>
可参考这个组件,自己封装
</el-tree>
Reference: encapsulated VUE tree
<My-tree
ref="Mytree"
slot="sidebar"
:data="tree.data"
height="5rem"
@check-change="checkChange"
style="margin-top: 0.1rem;">
</My-tree>
> Then implement the checkChange method to select checkedBox, first upload the code and then explain (pay attention to the remarks).
checkChange(data, node){ //选中的功能方法,你的tree中实现了吗?
console.log("是否选中", data,"选中的群组id",node);
//实现遍历选中功能,选中父类,遍历父类下的子孙类,比如选中广东,它下面的广州、深圳(宝安区、南山区)。。。。
this.setChildrenChecked(node, node.checked);
//遍历父类功能
if(node.checked){//如果选中
this.setParentChecked(node);//这个是子类选中,父类不被选中(看个人需求,不需要则禁用)
}else{
this.setParentUnCheck(node);/取消子类时,父类跟着被取消
}
},
Call the recursive method above
setChildrenChecked(node, isChecked) { // 递归子节点
node.checked = isChecked;
if (!node.children || node.children.length === 0) {
return;
}
for (let child of node.children) {
this.setChildrenChecked(child, isChecked);
}
},
setParentChecked(node) {//选中状态
if (!node.parent) {
return;
}
/* 这个是选中孙类(南山区),父类被选中(深圳),第一级不被选中(广东)
let allSameLevel = true; // 判断所有同级是否和当前状态一样
for (let sameLevel of node.parent.children) {
if (!sameLevel.checked) {
allSameLevel = false;
break;
}
}
if (!allSameLevel) { // 有不同的就不继续执行
return;
}
*/
node.parent.checked = true;
this.setParentChecked(node.parent);
},
setParentUnCheck(node){//未选中
if (!node.parent) {
return;
}
/* 孙节点取消(南山区),子节点跟着取消(深圳),父节点没有取消(广东)
let allSameLevel = false;
for (let sameLevel of node.parent.children) {
if (sameLevel.checked) {
allSameLevel = false;
break;
}
}
if (!allSameLevel) { // 有不同的就不继续执行
return;
}
*/
node.parent.checked = false;
this.setParentUnCheck(node.parent);
},
The above code has been implemented and the verification is OK.
The tree structure is roughly as follows (locally, Guangdong Province):