el-tree 点击父节点无效,只能选中子节点

背景:

el-tree树形控件点击的时候,我们不希望点击父节点,只希望点击子节点触发效果。

实际使用示例:摄像头树状图,根据不同市级区域划分,我们只希望点击子节点【摄像头】有效,点击具体的摄像头调取网络接口,点击市级区域不调取接口。

官网示例:

官网示例代码:

javascript 复制代码
<template>
  <el-tree
    style="max-width: 600px"
    :data="data"
    :props="defaultProps"
    default-expand-all
    @node-click="handleNodeClick"
  />
</template>

<script lang="ts" setup>
interface Tree {
  label: string
  children?: Tree[]
}

const handleNodeClick = (data: Tree) => {
  console.log(data)
}

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>

备注:从上面这个示例我们可以知道,点击父节点或者点击子节点都会触发节点点击事件,即触发节点点击事件@node-click="handleNodeClick"

要想仅仅点击子节点触发事件@node-click="handleNodeClick",需要在handleNodeClick事件内部判断点击的是否是子节点或者父节点,满足条件在执行,否则不执行。

实际效果图:

备注:在这个实际代码中,我们就可以判断type=== 100是否满足条件,满足的执行,不满足的不执行。

相关推荐
Hilaku2 小时前
作为面试官,我最怕遇到什么样的候选人?
前端·javascript·程序员
一 乐2 小时前
自习室座位预约管理系统|基于springboot + vue自习室座位预约管理系统(源码+数据库+文档)
java·vue.js·spring boot
TiDi2 小时前
Pinia优化重复请求
前端
web3d5202 小时前
01-用 Leafletjs 10 分钟搭一张水利一张图(Vue3 + Vite 实战)
前端·javascript
晚安日记wanna2 小时前
Vue2 的 defineProperty 差在哪四层追问筛掉九成候选人
前端·vue.js·面试
TiDi2 小时前
吸顶导航交互实现
前端
kisshyshy2 小时前
从Props透传到自定义Hook:系统梳理React跨层级通信与逻辑复用
前端·架构·代码规范
yume_sibai2 小时前
05-Flutter实战项目
前端·flutter
涛涛ing3 小时前
React 19.3 发布,但真正的赢家是 StyleX:当 AI 成为框架的“第一用户”
前端
zhangminghuan3 小时前
Vue vs React 实战拓展面试题|摒弃基础八股,聚焦业务开发核心难点(2026前端进阶)
前端