element-plus的el-tree的双向绑定

el-tree改造了下

可选可取消 有默认值 不包含父级id 默认展开 点击节点也可触发选择 节点内容自定义

javascript 复制代码
<template>
  {{ childKeys }}
  <!--
  default-checked-keys:默认展开值(正常来说需要包含父级id的 但是我们后端不要后端id )
  show-checkbox:多选框
  node-key:每个树节点用来作为唯一标识的属性,整棵树应该是唯一的
  default-expand-all:是否默认展开所有节点
  expand-on-click-node:是否在点击节点的时候展开或者收缩节点, 默认值为 true,如果为 false,则只有点箭头图标的时候才会展开或者收缩节点
  default-checked-keys:默认勾选的节点的 key 的数组
  check-on-click-node:是否在点击节点的时候选中节点,默认值为 false,即只有在点击复选框时才会选中节点
  props:配置选项,具体看下表
   -->
  <el-tree ref="treeRef" style="max-width: 600px" :data="data" show-checkbox node-key="id" :default-expand-all="true"
    :expand-on-click-node='false' :default-checked-keys="childKeys" :check-on-click-node="true" :props="defaultProps"
    @check-change="checkChange">
    <template #default="{ node, data }">
      <span class="custom-tree-node">
        <span>{{ node.label }}</span>
        <span style="color:red;margin-left: 10px">id:{{data.id }}</span>
      </span>
    </template>
  </el-tree>
</template>

<script setup>
import { ref } from 'vue';

let treeRef = ref(null);
let childKeys = ref([5, 10]); // 初始化选中子节点的 ID
const defaultProps = {
  children: 'children',
  label: 'label',
};

const data = [
  {
    id: 1,
    label: 'Level one 1',
    children: [
      {
        id: 4,
        label: 'Level two 1-1',
        children: [
          {
            id: 9,
            label: 'Level three 1-1-1',
          },
          {
            id: 10,
            label: 'Level three 1-1-2',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: 'Level one 2',
    children: [
      {
        id: 5,
        label: 'Level two 2-1',
      },
      {
        id: 6,
        label: 'Level two 2-2',
      },
    ],
  },
  {
    id: 3,
    label: 'Level one 3',
    children: [
      {
        id: 7,
        label: 'Level two 3-1',
      },
      {
        id: 8,
        label: 'Level two 3-2',
      },
    ],
  },
];

const checkChange = () => {
  // 获取所有选中的节点对象
  const checkedNodes = treeRef.value.getCheckedNodes();

  // 结果1:获取包含父节点的id
  childKeys.value = treeRef.value.getCheckedKeys()

  // 结果2:提取子节点的 ID,不包括父节点
  childKeys.value = checkedNodes
    .filter(node => !node.children) // 只保留没有子节点的节点
    .map(node => node.id); // 提取 ID

  console.log('默认值', childKeys.value, checkedNodes); // 只包含子节点的 ID
}
</script>
相关推荐
wuhen_n6 小时前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
大鱼前端7 小时前
为什么我说CSS-in-JS是前端“最佳”的糟粕设计?
前端
不爱吃糖的程序媛7 小时前
Capacitor:跨平台Web原生应用开发利器,现已全面适配鸿蒙
前端·华为·harmonyos
AC赳赳老秦7 小时前
2026国产算力新周期:DeepSeek实战适配英伟达H200,引领大模型训练效率跃升
大数据·前端·人工智能·算法·tidb·memcache·deepseek
CHU7290357 小时前
淘宝扭蛋机抽盒小程序前端功能解析:解锁趣味抽盒新体验
前端·小程序
-凌凌漆-7 小时前
【npm】npm的-D选项介绍
前端·npm·node.js
鹿心肺语7 小时前
前端HTML转PDF的两种主流方案深度解析
前端·javascript
海石7 小时前
去到比北方更北的地方—2025年终总结
前端·ai编程·年终总结
一个懒人懒人8 小时前
Promise async/await与fetch的概念
前端·javascript·html
Mintopia8 小时前
Web 安全与反编译源码下的权限设计:构筑前后端一致的防护体系
前端·安全