el-tree设置有子元素的节点不能选中高亮(vue3+ts写法)

思路:

  1. el-tree加上highlight-current属性,高亮当前选中节点
  2. el-tree的点击事件@node-click中判断有子元素的节点不能选中高亮,核心代码node.isCurrent = false,让当前节点取消选中
  3. 这时需要找到上次高亮的节点,让它继续选中高亮,思路是通过node-keycurrent-node-key属性还原高亮节点
<template>
  <el-tree 
      :data="data" 
      :props="defaultProps" 
      @node-click="handleNodeClick" 
      highlight-current  
      node-key="id"  
      :current-node-key="currentNodeKey"
      default-expand-all
      :expand-on-click-node="false"/>
template>

<script lang="ts" setup>
import type Node from 'element-plus/es/components/tree/src/model/node'
import { ref, nextTick } from "vue"
interface Tree {
  label: string
  children?: Tree[]
}

const currentNodeKey = ref("")
const treeId = ref("")
const handleNodeClick = (data: Tree, node: Node) => {
    // 有子元素的节点,不能选中
    if (data.children.length) {
        node.isCurrent = false
         // 还原之前的高亮节点
        currentNodeKey.value = ""
        nextTick(() => {
          currentNodeKey.value = treeId.value
        })
        return
    }
    treeId.value = data.id
    // 点击树节点执行的代码
    ...
}

const data: Tree[] = [
  {
    label: 'Level one 1',
    children: [
      {
        label: 'Level two 1-1',
        children: [
          {
            label: 'Level three 1-1-1',
          },
        ],
      },
    ],
  },
  {
    label: 'Level one 2',
    children: [
      {
        label: 'Level two 2-1',
        children: [
          {
            label: 'Level three 2-1-1',
          },
        ],
      },
      {
        label: 'Level two 2-2',
        children: [
          {
            label: 'Level three 2-2-1',
          },
        ],
      },
    ],
  },
  {
    label: 'Level one 3',
    children: [
      {
        label: 'Level two 3-1',
        children: [
          {
            label: 'Level three 3-1-1',
          },
        ],
      },
      {
        label: 'Level two 3-2',
        children: [
          {
            label: 'Level three 3-2-1',
          },
        ],
      },
    ],
  },
]

const defaultProps = {
  children: 'children',
  label: 'label',
}
script>

你可能感兴趣的:(javascript,前端,vue.js)