el-tree自动展开选中节点 并自动定位到选中节点
在Element UI中,el-tree
组件提供了default-expanded-keys
属性来设置默认展开的节点,并且可以通过current-node-key
属性来高亮(也就是定位)当前选中的节点。以下是一个简单的实例代码,展示了如何在el-tree
中自动展开并定位到选中的节点:
<template> <el-tree :data="treeData" :props="defaultProps" :default-expanded-keys="defaultExpandedKeys" :current-node-key="currentNodeKey" @node-click="handleNodeClick" ></el-tree> </template> <script> export default { data() { return { treeData: [ // 树形结构的数据 ], defaultProps: { children: 'children', label: 'label' }, defaultExpandedKeys: [], currentNodeKey: null }; }, watch: { // 监听选中节点的变化,自动展开并定位 'currentNodeKey'(newKey) { if (newKey) { this.defaultExpandedKeys = [newKey]; } } }, methods: { handleNodeClick(data, node) { this.currentNodeKey = data.id; // 假设节点数据中有唯一标识id字段 } } }; </script>
在这个例子中,当用户点击一个节点时,handleNodeClick
方法会被调用,并且更新currentNodeKey
。watch
属性会监听currentNodeKey
的变化,一旦发生变化,就会将defaultExpandedKeys
更新为新的选中节点的id
,从而自动展开选中的节点。
https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=el-tree%E8%87%AA%E5%8A%A8%E5%B1%95%E5%BC%80%E9%80%89%E4%B8%AD%E8%8A%82%E7%82%B9%20%E5%B9%B6%E8%87%AA%E5%8A%A8%E5%AE%9A%E4%BD%8D%E5%88%B0%E9%80%89%E4%B8%AD%E8%8A%82%E7%82%B9%20&oq=el-tree%25E5%25B1%2595%25E5%25BC%2580%25E6%258C%2587%25E5%25AE%259A%25E8%258A%2582%25E7%2582%25B9&rsv_pq=a45ce59900efa52b&rsv_t=eeb5zupwsxk%2BPgNPklyjTEZsE16pY1U0O33Wwbk993nGCOMCHNZhZPt897A&rqlang=cn&rsv_enter=0&rsv_dl=tb&rsv_btype=t&inputT=971&rsv_sug3=27&rsv_sug1=37&rsv_sug7=100&rsv_n=2&rsv_sug4=971