element-ui中tree形控件节点默认展开的动态设置

element-ui中tree形控件节点默认展开的动态设置

业务需求

模糊搜索时,需要tree展开搜索的节点,如下图所示

Snipaste_2023-01-06_10-03-11.png
Snipaste_2023-01-06_10-05-07.png

实现

tree组件中的default-expand-all属性控制是否默认展开所有节点,因tree组件中节点太多,该属性并不能直接设置为true,我给了一个默认为false的变量openShow,data中定义false

<el-tree
        :default-expand-all="openShow"
        :lazy="isLazy"
        :load="loadNode"
        id="my-tree"
        ref="tree"
        class="tree-view structure-tree scroll-bar"
        :data="treeData"
        node-key="treeId"
        highlight-current
        :props="defaultProps"
        @node-click="handleNodeClick"
        :auto-expand-parent="true"
        :expand-on-click-node="false"
      ></el-tree>

本人项目中使用了lazy懒加载,当需要模糊搜索展开时,不需要懒加载,所以同理给了lazy属性默认为true的变量isLazy,data中定义为true

本人搜索采用了el-select下拉框,在watch中监听el-select下拉框

searchValue(val) {
      if (val) {
        this.choiceHouse(val);
      } else {
        this.treeData = [
          {
            treeName: "鄞州区",
            id: 1,
            treeId: 1,
            treeType: 0,
            children: [],
            isChildren: false,
          },
        ];
        this.openShow = false
        this.isLazy = true
      }
    },

this.choiceHouse(val)是获取搜索的节点的路径,在该方法中,设置

 this.openShow = true
 this.isLazy = false

通过以上代码,会发现搜索后,default-expand-all 属性为true,tree节点并不会默认展开

222.png

此时需要使用key去处理树的重载,给tree添加key属性,data中定义为 ""

<el-tree
        :key="treeKey"
        :default-expand-all="openShow"
        :lazy="isLazy"
        :load="loadNode"
        id="my-tree"
        ref="tree"
        class="tree-view structure-tree scroll-bar"
        :data="treeData"
        node-key="treeId"
        highlight-current
        :props="defaultProps"
        @node-click="handleNodeClick"
        :auto-expand-parent="true"
        :expand-on-click-node="false"
      ></el-tree>

然后在watch监听中添加

this.treeKey = +new Date();

此时代码如下:

searchValue(val) {
      if (val) {
        this.choiceHouse(val);
        // 使树重新渲染
        this.treeKey = +new Date();
      } else {
        this.treeData = [
          {
            treeName: "鄞州区",
            id: 1,
            treeId: 1,
            treeType: 0,
            children: [],
            isChildren: false,
          },
        ];
        this.openShow = false
        this.isLazy = true
        // 使树重新渲染
        this.treeKey = +new Date();
      }
    },

前端菜鸟发文,如果此文章对你有所帮助的话,记得点个赞再走

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容