反向递归,树组件常用逻辑

示例图

在这里插入图片描述
在这里插入图片描述

树节点方法

/**
 * 递归组装数据
 * options 数结构
 * code 最后一级的 id
 * parentHalfKeys 半选的父节点节点
 */
recursion(options, code, parentHalfKeys) {
  let result = [], // 递归结果
  tempArry = []; // 缓存数据
  // arry 数据源 code 最后一级数据
  const arryMap = (arry, code) => {
    arry.map((item, index) => {
      if (item.children) {
        tempArry.push({name: item.name, code: item.id, number: item.spu_count});
        arryMap(item.children, code);
      } else if (item.id == code) {
        tempArry.push({name: item.name, code: item.id, number: item.spu_count});
        result = [...tempArry];
      } 
      if (index == arry.length - 1) {
        tempArry.pop();
      }
    });
  }
  arryMap(options, code);
  // 如果当前的子节点中的父节点在半选的节点数组中有,则取子节点的数据,否则取父节点的数据
  if (parentHalfKeys.find(item => item === result[0].code)) {
    return {label: result[result.length - 1].name, number: result[result.length - 1].number, code: result[result.length - 1].code}
  } else {
    return {label: result[0].name, number: result[0].number, code: result[0].code}
  }
},

调用

// 确定
handleConfirm() {
  let selectedList = this.$refs.treeNode.getCheckedKeys(true); // 选中的最后一级子节点
  let parentHalfKeys = this.$refs.treeNode.getHalfCheckedKeys(); // 获取半选的节点
  let resultList = []; // 最终的结果数据,需要过滤
  selectedList.forEach(item => {
    let result = this.recursion(this.classification_list, item, parentHalfKeys);
    if (JSON.stringify(resultList).indexOf(result.code) === -1) {
      resultList.push(result);
    }
  });
  console.log(resultList);
}

结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值