antd-Vue tree 在父子节点关联的情况下,在只有一个子元素,选中子元素时父元素也会选中的情况下获取子元素的key
如图:只想要"dfdfgf"和"信息新增"的id;
在每次选中元素时,tree的 @check="onCheck"可以得到checkedKeys,里面的第一项是选中的元素的key,先保存下来。
onCheck (checkedKeys, info) {
this.checkedKeys = checkedKeys
this.leaf=[...checkedKeys]
this.neArr = [...checkedKeys];
},
再去watch “checkedKeys” 的变化,在info里可以看到checkedKeys的变化,将info
也保存起来。当this.leaf的length大于 this.selectLeaf的length,说明是添加了元素,将先添加的第一元素找到,将第一个元素以及它下面的所有的子元素全部都放到this.selectedAdd。当this.leaf的length小于 this.selectLeaf的length,说明是取消了选中的元素,这时this.leaf就是当前选中的全部元素。可以直接 this.selectedAdd=this.leaf;
最后 this.selectedAdd是所有想选中的元素。
watch: {
checkedKeys (val, info) {
console.log(info);
this.selectLeaf=info;
let arr=[];
let result =[...this.treeData];//树形结构的数据
let tem=[];
console.log(this.leaf,"1");
console.log(this.selectLeaf,'2');
if(this.leaf.length > this.selectLeaf.length){
arr=this.filterArr(this.leaf,this.selectLeaf);//将两个数组中相同的元素去掉
tem= this.getChild(result,arr[0],[]);//寻找当前元素的所有子元素
this.selectedAdd.push(...tem);
}else{
this.selectedAdd=this.leaf;
}
}
},
根据当前元素查找它的所有的子元素
getChild(nodes, item, arr) {
for (let el of nodes) {
if (el.key === item) {
arr.push(el.key);
if (el.children) {
this.childNodesDeep(el.children, arr);
}
} else if (el.children) {
this.getChild(el.children, item, arr);
}
}
return arr;
},
childNodesDeep(nodes, arr) {
if (nodes)
nodes.forEach((ele) => {
arr.push(ele.key);
if (ele.children) {
this.childNodesDeep(ele.children, arr);
}
});
}
,
去掉两个数组中相同的元素
filterArr (arr1, arr2) {
const arr = [...arr1, ...arr2];
const newArr = arr.filter((t) => {
return !(arr1.includes(t) && arr2.includes(t));
});
return newArr;
}
这是我的办法,要是大家有更好的,更简便的方法可以@我一下