vue3 基于el-tree增加、删除节点(非TypeScript 写法)

话不多说,直接贴代码

java 复制代码
<template>
  <div class="custom-tree-container">
    <!-- <p>Using render-content</p>
    <el-tree style="max-width: 600px" :data="dataSource" show-checkbox node-key="id" default-expand-all
      :expand-on-click-node="false" :render-content="renderContent" /> -->
    <p>Using scoped slot</p>
    <el-tree style="max-width: 600px" :data="dataSource" show-checkbox node-key="id" default-expand-all
      :expand-on-click-node="false">
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <a @click="append(data)"> Append </a>
            <a style="margin-left: 8px" @click="remove(node, data)"> Delete </a>
          </span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script>
import { reactive, ref, toRefs } from 'vue'
// import {Node} from 'element-plus/es/components/tree/src/model/node'

export default {
  name: 'part',
  setup() {
    const state = reactive({
      dataSource: [
        {
          id: 1,
          label: 'Level one 1',
          children: [
            {
              id: 4,
              label: 'Level two 1-1',
              children: [
                {
                  id: 9,
                  label: 'Level three 1-1-1'
                }
              ]
            }
          ]
        }
      ]
    })

    const append = (data) => {
      let treeNodeId = data.$treeNodeId;
      console.info(data)
      // alert('当前id'+data.id)
      // alert(data.$treeNodeId)
      let id =data.id*100+1
      const newChild = { id: id, label: data.label+'-'+id, children: [] };
      if (!data.children) {
        data.children = [];
      }
      data.children.push(newChild);
      // state.dataSource = [data];
    }

    const remove = (node, data) => {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
      // dataSource.value = [...dataSource.value];
    };

    return {
      ...toRefs(state),
      append,
      remove
    }
  }
}




</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>

效果如下

相关推荐
老华带你飞7 小时前
二手商城|基于springboot 二手商城系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
文心快码BaiduComate7 小时前
给 AI 装上“员工手册”:如何用Rules 给文心快码 (Comate) 赋能提效?
前端·程序员·前端框架
哆啦A梦15887 小时前
商城后台管理系统 06 Mock.js模拟数据
开发语言·javascript·ecmascript
老华带你飞7 小时前
酒店预约|基于springboot 酒店预约系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
twl7 小时前
注意力机制在Code Agent的应用
前端
涔溪8 小时前
如何使用 CSS Grid 实现响应式布局?
前端·css
黛色正浓8 小时前
leetCode-热题100-哈希合集(JavaScript)
javascript·leetcode·哈希算法
未来读啥科教资讯8 小时前
2026年深圳国际户外用品展览会参展效果如何?影响力如何?
前端
码农胖大海8 小时前
浏览器及标签页关闭时登出的解决方案
前端·浏览器
喵爸的小作坊8 小时前
StreamPanel:一个让 SSE 调试不再痛苦的 Chrome 插件
前端·后端·http