天天看点

页面跳转,el-tree动态设置选中节点样式

需求就是从A页面点击名称,跳转到B页面,选中B页面的树节点并查询对应的数据。

这里的树形结构,并没有使用勾选框,选中的样式也进行了一些修改。

一开始没发现el-tree有设置默认选中的属性,还在想怎么操作dom实现该功能。

仔细看文档还是很重要的~

current-node-key可以实现我们想要的功能。但是有些坑需要注意。

页面跳转,el-tree动态设置选中节点样式
页面跳转,el-tree动态设置选中节点样式

1.先重写el-tree-node 选中的默认样式.。观察dom发现点击树节点后该节点会加上is-current样式,所以主要是修改is-current的样式类。

/deep/ .el-tree-node.is-current > .el-tree-node__content {
        background: rgba(22, 119, 255, 0.1);
        border-right: 3px solid #1677ff;
        color: #187aff;
        /deep/ .el-tree-node__expand-icon {
          color: rgb(0, 112, 255);
        }
        /deep/ .is-leaf {
          color: rgba(0, 0, 0, 0);
        }
      }
           

2.el-tree设置 node-key 和 currentNode

页面跳转,el-tree动态设置选中节点样式

3.监听路由,并执行查询函数

watch: {
    $route(from, to) {
      console.log('route to', from, to)
      console.log('params', this.$route.params)

      if (this.$route.params.row) {
        const row = {
          value: from.params.row.acc_name,
          id: from.params.row.acc_code
        }
        this.clickQuery(row)
      }
    }
  },

  // 查询数据
    clickQuery(row) {
      console.log('query', row)
      if (row) {
        this.acc_name = row.value
        // 根据编码去查询数据
        this.popoverForm.acc_code = row.id
        // 设置选中的节点
        this.currentNode = row.id
        // 只是修改current-node-key的值,达不到效果。需要使用setCurrentKey属性,才能选中并高亮
        this.$refs.tree.setCurrentKey(row.id)

        this.refreshEvent()
      }
    },
           

注意事项:

这里有个坑,正常想法就是, 直接使用this.xxx 的方式去改变current-node-key的值,但是没有效果、

要实现选中该节点,并显示选中样式。需要使用setCurrentKey( )方法。

页面跳转,el-tree动态设置选中节点样式

详细请看这篇文章的采坑实录

Element树形控件Tree踩坑:修改current-node-key无效