Bootstrap

elementUI中el-tree组件单选没有复选框时,选中、current-node-key高亮、刷新后保留展开状态功能的实现

一、代码实现

1. 属性了解 (更多

  1. node-key 每个树节点用来作为唯一标识的属性,整棵树应该是唯一的 String
  2. current-node-key 当前选中的节点 string, number
  3. expand-on-click-node 是否在点击节点的时候展开或者收缩节点, 默认值为 true,如果为 false,则只有点箭头图标的时候才会展开或者收缩节点。 boolean — true
  4. default-expand-all 是否默认展开所有节点 boolean — false
  5. highlight-current 是否高亮当前选中节点,默认值是 false。 boolean — false
  6. check-on-click-node 是否在点击节点的时候选中节点,默认值为 false,即只有在点击复选框时才会选中节点。 boolean — false

2. 实现步骤

  1. 设置一个固定值 node-key=“id”, 根据实际项目配置唯一的标记

  2. 定义当前选中节点 :current-node-key=“currentDeptId”

  3. 设置highlight-current为true

  4. 设置current-node-key为currentDeptId,同时刷新接口时重新设置currentDeptId,代码如下

    this.$nextTick(() => {
     this.$refs['tree'].setCurrentKey(this.currentDeptId);
    })
    

    3.代码示例

    1.html部分

      <el-tree :data="deptOptions" :props="defaultProps" node-key="id" :expand-on-click-node="false"
           ref="tree" default-expand-all highlight-current @node-click="handleNodeClick"
              :current-node-key="currentDeptId" :check-on-click-node="true">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span>{{ node.label }} </span>
              </span>
       </el-tree>
    
    1. js部分:
       // 部门树选项
        deptOptions: undefined,
      // 配置选项
        defaultProps: {
            children: "children",
            label: "label",
        },
         //默认选中的部门
         currentDeptId: null,   // 比如:107
         currentDeptName: null, 
    	  methods: {
    	      // 节点单击事件
    	      handleNodeClick(data) {
    	          console.log(data, '节点单击事件')
    	          this.currentDeptId = data.id
    	          this.currentDeptName = data.label
    	      },
    	     }
    

    根据实际需要,在刷新下拉树的时候,这个currentDeptId,需要重置。(以便在刷新后,保留刷新前的选中状态)

     /** 查询下拉树结构 */
            getTreeselect() {
                deptTreeselect({
                 
                }).then((response) => {
                    this.deptOptions = response.data;
                    // 设置highlight-current为true
                    // 设置current-node-key为currentDeptId,同时刷新接口时重新设置currentDeptId,新后保留展开状态功能的实现 ,代码如下
                    // 设置选中
                    this.$nextTick(() => {
                        this.$refs["tree"].setCurrentKey(this.currentDeptId);
                    });
                });
            },
    
    1. css部分
    <style scoped>
    /*  鼠标hover改变背景颜色 */
      /deep/ .el-tree-node  .el-tree-node__content:hover {
        background-color: #f0f7ff !important;
        color: #409eff;
      }
      /*  颜色高亮 */
      /deep/ .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
        color: #409eff;
      }
    </style>
    

    二、 效果图

    在这里插入图片描述

;