And design tree 自动收起同级 只展开一个文件夹 expand的坑

本文详细讲述了如何在前端开发中实现一个可自定义点击行为的树形组件,并重点介绍了如何处理节点展开与收缩、`onExpand`函数中的`expandedKeys`更新技巧以及使用`loop`函数遍历父级节点。作者分享了在处理`expandedKeys`时遇到的坑和解决方案,适合对Vue或React树形组件有需求且需要扩展功能的开发者。
摘要由CSDN通过智能技术生成

需求要,但UI没这功能 上代码

<a-tree
      :autoExpandParent="false" //加上
      :treeData="treeData"
      :expandedKeys.sync="expandedKeys"
      @expand="onExpand"
      :showIcon="false"
    >
    //自定义树 可不加(主要是客户需要点击内容也要收起展开)
    <div
        slot="action"
        slot-scope="record"
        @click="clickTree(record.key, record)"
      >

函数

 onExpand(a, b) {
 	  // b 就是选中的node对象 很复杂
      var key = b.node.eventKey
      var record = b.node.dataRef
      this.clickTree(key, record)
      // 巨坑!!!注意这里的a也就是expandedKeys,但是直接赋值无效,要splice截取全部后添加当前this.expandedKeys
      a.splice(0, a.length, ...this.expandedKeys)
      return
    },
    clickTree(key, record) {
      const index = this.expandedKeys.indexOf(key)
      if (index > -1) {
        // 存在
        this.expandedKeys.splice(recordKey, 1)
      } else {
        this.expandedKeys = []
        this.expandedKeys.push(key)
        this.findDadObj(record)
      }
    },
    loop(data, key, callback) {
      data.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index, arr)
        }
        if (item.children) {
          return this.loop(item.children, key, callback)
        }
      })
    },
    findDadObj(obj) {
    // 没父级id就返回
      if (!obj.parentId) {
        return
      }
      // 循环总数据 取出父级ID的数据对象,塞入Id并再查找父级
      this.loop(this.treeData, obj.parentId, (item) => {
        this.expandedKeys.push(item.key)
        this.findDadObj(item)
      })
    },

主要是靠LOOP循环出当前选择的父级ID全部塞到expandedKeys数组里

// 巨坑!

!!注意expand函数的a也就是expandedKeys,直接赋值无效,要splice截取全部后添加当前this.expandedKeys,或者你们用$set试试

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值