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方法中先设置传入节点的展开状态,然后判断此节点是否有父节点,有的话递归调用自身,达到展开所有祖节点的目的。