el-tree设置默认展开及选中

设置默认展开

default-expanded-keys的值设为想展开的node-key值对应的数组即可,此处的choiceId设置为常量1,展开的是id为1的节点

  <el-tree ref="tree"
                   :data="treeData"
                   highlight-current
                   node-key="id"
                   :props="defaultProps"
                   :default-expanded-keys="[1]"
                   :filter-node-method="filterNode">
 </el-tree>

设置为默认选中转态

设置默认展开后你会惊奇的发现,这没人性的设计居然没有设置选中状态!!!惊喜不惊喜,意外不意外!!不过没关系,见招拆招,此时需要使用方法setCurrentKey进行设置,若发现此法报错则需加入$nextTick()解决,

此处将展开默认id为1的对象

如下

this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(1)
      })

设置选中状态的css样式

el-tree默认的显示状态是不明显的,给它加上css样式即可显示出想要的效果,

未加样式的效果

加了样式的效果

注意:此法el-tree需要加上 highlight-current属性

代码:

/deep/.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #409eff;
  color: white;
}

设置编辑后默认展开与选中

如下当用户对树的数据进行增删改时,此处选择的方案是重新像后台请求回来数据进行刷新,此时init(初始化)函数应当可以继续使用

点击节点后需要将节点的值保留下来,在修改好节点之后就不会丢失该节点

  <el-tree ref="tree"
                   :data="treeData"
                   highlight-current
                   node-key="id"
                   :props="defaultProps"
                   :default-expanded-keys="[choiceId]"
                   :filter-node-method="filterNode"
				  @node-click="(data)=>{choiceId = data.id}"
				  >
 </el-tree>

此处init设置如下:

async init () {
      //获取后台返回的数据
      let resData = (await sqConfigTreeSearch()).data
      //递归构造树形数据
      function makeTree (pid) {
        const temp = []
        for (let i = 0; i < resData.length; i++) {
          if (resData[i].pid === pid) {
              //由于后台返回的字段没有label,此处需要另行添加
            resData[i].label = resData[i].name
            temp.push(resData[i])
            resData[i].children = makeTree(resData[i].id)
          }
        }
        return temp
      }
      this.treeData = makeTree(null)
    //第一次的choiceId设置为第一个数据,若之后设置了选中则无需更改
      this.choiceId === '' && (this.choiceId = this.treeData[0].id)
      //设置选中
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.choiceId)
      })
    },
原文地址:https://www.cnblogs.com/axu1997/p/13878860.html