element tree组件current-node-key 失效或者setCurrentKey失效问题解决方案

element tree组件current-node-key 失效或者setCurrentKey失效问题解决方案

在使用element-ui el-tree 组件时遇到设置默认高亮属性或方法不生效的问题,现在将解决方案贴出来:

首先先看html代码:

<el-tree
    :props="props"
    :data="data"
    node-key="id"
    @node-click="handleNodeClick"
    ref="treeSelect"
    :highlight-current="true"
    :current-node-key="currentKey"
    :expand-on-click-node="false">
    <span class="custom-tree-node" slot-scope="{ node }">
      <span class="customSapn" :title="node.label">{
   
   { node.label }}</span>
    </span>
</el-tree>
  • 首先保证设置 node-key 属性为数据中的唯一值,可以是id,也可以是其他。
  • 设置ref=“treeSelect”
  • 设置 :highlight-current=“true” 此属性表示设置选中项为高亮样式。

然后在data里配置

import { translateDataToTree } from '@/utils/utils'
data () {
    return {
        data:[],
        currentKey: '',
        props: {
            label: 'name', // 节点文本字段key
            children: 'children'
        }    
    }
}

在js里动态设置默认选中项

this.data = translateDataToTree(接口返回数据).treeData //treeData是接口返回的数据
this.currentKey = 'defaultId' // 默认选中id值
this.$nextTick(() => {
    
    
    this.$refs['treeSelect'].setCurrentKey(this.currentKey)
})

setCurrentKey方法放在$nextTick里使用。

当后端返回数据是一维数组,怎么转化成父子嵌套结构方法:

utils/utils.js:
/** 以下三个key名,以实际接口数据为准
* department_id  当前节点id字段名
* children       当前节点的子元素集合字段名
* parent_id      当前节点父id字段名
*/
export const translateDataToTree =(data) =>{
    
    
    data = JSON.parse(JSON.stringify(data))
    // 删除所有 children,以防止多次调用
    data.forEach(function (item) {
    
    
      delete item.children;
    });
    let map = {
    
    }; // 构建map
    data.forEach(i => {
    
    
      map[i.department_id] = i; // 构建以id为键 当前数据为值
    });
    let treeData = [];
    data.forEach(child => {
    
    
        const mapItem = map[child.parent_id]; // 判断当前数据的parentId是否存在map中
        if (mapItem) {
    
     // 存在则表示当前数据不是最顶层数据
            // 注意: 这里的map中的数据是引用了arr的它的指向还是arr,当mapItem改变时arr也会改变,踩坑点
            // 这里判断mapItem中是否存在children, 存在则插入当前数据, 不存在则赋值children为[]然后再插入当前数据
            (mapItem.children || ( mapItem.children = [] )).push(child)
        } else {
    
     // 不存在则是组顶层数据
            treeData.push(child);
        }
    });
    return {
    
    
      treeData: treeData,
    };
}

猜你喜欢

转载自blog.csdn.net/qq_35517283/article/details/129858175