工作笔记:vue中数据改为树形级联下拉格式

    /* 获取商品分类 */
    APGetGovCategoryTree() {
      APGetGovCategoryTree().then((res) => {
        // treeNames转为数组
        this.Category = res.list.map((item)=>{
          return {
            cate_id: item.id,
            categoryName: item.name,
            interfaceCode: item.interfaceCode,
            treeNames: item.treeNames.split('-').filter(items => items !== ''),
          }
        });
        // 数据转为树形结构
        this.CategoryList = this.Category.map(item => {
          let children=[];
          this.buildChildrenNode(children, item.treeNames)
          return children[0];
        })
        // 相同级别的相同分类合并
        this.changeList(this.CategoryList);
      });
    },

    // 商品分类转为树形结构
    buildChildrenNode(children, itemArr){
      for (let i in itemArr) {
          let node = {
            value: itemArr[i],
            label: itemArr[i],
          }
          children.push(node)
          if (i != itemArr.length - 1 && !children[children.length - 1].children) {
              children[children.length - 1].children = []
          }
          children = i == itemArr.length - 1 ? children : children[children.length - 1].children
      }
    },

    // 相同级别的相同分类合并
    changeList(data){
      for(let i=0; i<data.length-1; i++){
        for(let j=i+1; j<data.length; j++){
          if(i!=j && data[i].label==data[j].label){
            this.changeListchild(data[i].children,data[j].children);
            data.splice(j,1);
            j--;
          }
        }
      }
    },
    changeListchild(a,b){
      if(a && b){
        if(a[0].label == b[0].label){
          this.changeListchild(a[0].children,b[0].children);
        }
        if(a[0].label != b[0].label){
          a.push(b[0]);
          this.changeList(a);
        }
      }      
    },

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值