地区选择器,通过最后一级id逐层找到他对应的父级

递归写法

//通过最后一级id即countryId,查找前面两级id
findAncestorsById(tree, id, result = []) {
      for (const node of tree) {
        if (node.value === id) {
          result.push(id);
          return result;
        }
        if (node.children && node.children.length) {
          const temp = this.findAncestorsById(node.children, id, result);
          if (temp) {
            result.push(node.value);
            return result;
          }
        }
      }
      return null;
    },

可以在生命周期中调用

    if (this.tempValue && this.tempValue !== '0') {
      console.log(this.tempValues);
      this.value = this.findAncestorsById(this.options, this.tempValue)
      this.value = this.value.reverse()
    }

通过这个方法可以得到一个数组,但是是反序的,需要通过reverse()翻转,等到符合el-cascader的数组结构,那么就可以通过后端返回的最后一级id,找到前面几级的id,正常渲染数据了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值