element 树形控件el-tree展开所有父节点

如果你在使用el-tree组件时,想实现把当前选中节点的所有父节点都展开,可以使用下面方法。

<el-tree
    ref="tree"
     :data="options"
     @node-click="handleNodeClick"
     :highlight-current="true"
     :current-node-key="activeOption"  
     :props="treeProps"
     :node-key="treeProps.id"
     :check-on-click-node="true"
     class="option-tree"
   />

注:current-node-key设置选中节点时一定要设置node-key

监听传入的选中值:

props:{
	selected: { // 这是选中的节点
      type: [String, Number],
      default: () => {
        return ''
      }
    }
},
watch: { 
    selected (val) {  //监听选中节点变化,如果不是传递过来的数据就监听activeOption
      val && (this.activeOption = val)
      val && this.$refs.tree.setCurrentKey(val)
      const selected = this.$refs.tree.getCurrentNode()
      // 若当前组件有父节点 展开其所有祖宗节点
      if (this.$refs.tree.getNode(selected) && this.$refs.tree.getNode(selected).parent) {
        this.expandParents(this.$refs.tree.getNode(selected).parent)
      }
      // this.$emit('filterSelect', selected)
    }
  },
  methods: {
  	// 展开所有祖宗节点
    expandParents (node) {
      node.expanded = true
      if (node.parent) {
        this.expandParents(node.parent)
      }
    }
  }

当传入的选中值变化时,判断其存在,存在时使用setCurrentKey方法设置选中值(key)对应的节点的选中状态;然后利用getCurrentNode方法获得当前选中的节点;接着判断当前选中节点是否有父节点,有则传入expandParents方法改变其父节点的展开(expand)状态。
在expandParents方法中先设置传入节点的展开状态,然后判断此节点是否有父节点,有的话递归调用自身,达到展开所有祖节点的目的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值