vue 项目使用element ui 中tree组件 check-strictly 用法(父子不互相关联的反显情况)

属性 check-strictly:

      在显示复选框的情况下,是否严格遵循父子互相关联的做法,默c认为 false。

      默认false,父子关联。

           点击父节点,其下子节点全部统一跟随父节点变化,点击子节点,子节点部分勾选时,父节点处于半选状态。

     设置为true,严格遵循父子不互相关联。

            就是点击全选的话,是可以全选上,可以把父级对应的子级取消掉,保留父级这个选择

代码如下:

<el-tree
ref="tree"
:data="treeData"
:props="defualtProps"
show-checkbox
node-key="id"
check-on-click-node
:default-expand-all="true"
:default-checked-keys="checkedId"
:check-strictly="checkStrictly"
:expand-on-click-node="false"
@check="checkTree"
/>
//js
...
data(){
return{
checkStrictly:true,
checkedId:[],
treeData:[],
defaultProps:{ //这里目的是为了防止,后台返回的数据字段不包含label,或者children
children:'children',
label:'content',
},
clearSelectIds: []
}
}
methods:{
//check 事件,传入两个参数,依次为:传递给 data 属性的数组中 该节点所对应的对象,
// 树目前的选中状态对象(包含 checkedNodes , checkedKeys , halfCheckedNodes, halfCheckedKeys 四个属性)
checkTree(currentObj, treeStatus){
const selectedId = treeStatus.checkedKeys.indexOf(currentObj.id);
if(selected !== -1){
this.selectedParent(currentObj);
this.uniteChildSame(currentObj,true,currentObj.id);
}else{
if(currentObj.children.length > 0){
this.clearSelectIds = [];
this.clearSelectedByChild(currentObj, treeStatus);
}
if(!currentObj){
this.uniteChildSame(currentObj,false,currentObj.id);
}
}
},
clearSelectedByChild(currentObj,treeStatus,childrenId){
const { checkedKeys } = treeStatus;
const children = currentObj.children ? currenObj.children : currentObj;
let selectedId = [];
const childrenIds = childrenId ? [...childrenId] : [];
for(let i=0,len=children.length;i<len;i+=1){
childrenIds.puch(children[i].id);
this.clearSelectIds.push(children[i].id);
if(children[i].children.length>0){
this.clearSelectedByChild(children[i], treeStatus, childrenIds);
}
}
selectedId = checkedKeys.filter((item) => this.clearSelectIds.indexOf(item) === -1);
this.$refs.tree.setCheckedKeys(selectedId);
},
uniteChildSame(treeList, isSelected, id){
this.$refs.tree.setChecked(id, isSelected);
const {children} = treeList;
for(let i=0,len=children.length;i<len;i+=1){
this.uniteChildSame(children[i], isSelected, children[i].id);
if(children[i].children.length>0){
this.uniteChildSame(children[i].children, children[i].children.id);
}
}
},
selectedParent(currentObj){
const currentNode = this.$refs.tree.getNode(currentObj);
if(currentNode.parent.key !== undefined){
this.$refs.tree.setChecked(currentNode.parent, true);
this.selectedParent(currentNode.parent);
}
}
}
...

效果大概就是这样子:

     勾选父级,下面的子级就会选中。

     假设,父级是处于选中状态,子级也是选中状态,然后,取消子级的选中状态(该父级下面的子级全部取消选中状态),此时,如果不是主动取消父级的选中状态,是可以做到保留父级的选中状态哦。

参考链接:https://blog.csdn.net/Beam007/article/details/87858291

如果快乐太难,那祝你平安。
原文地址:https://www.cnblogs.com/sunnyeve/p/14448583.html