element-ui中tree节点默认展开动态设置

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

业务需求

模糊搜索时,需要tree展开搜索的节点,如下图所示
在这里插入图片描述

在这里插入图片描述

实现

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节点并不会默认展开

在这里插入图片描述

此时需要使用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();
      }
    },

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

猜你喜欢

转载自blog.csdn.net/weixin_67644104/article/details/128575037