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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM