antd-Vue tree 在父子节点关联的情况下,在只有一个子元素,选中子元素时父元素也会选中的情况下获取子元素的key

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;
}

这是我的办法,要是大家有更好的,更简便的方法可以@我一下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值