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>

效果如下

相关推荐
gc_229938 分钟前
Vue框架学习(1:环境搭建)
vue.js
原则猫1 小时前
UDP 到底怎么实现可靠的
前端
Java后端的Ai之路1 小时前
14、ReactJS - 路由(Router)
前端·react.js·状态模式
持敬chijing2 小时前
白盒测试与代码审计-js登录逆向实战
javascript·网络·安全·web安全·网络安全·网络攻击模型
优选资源分享2 小时前
PicGo v3.0.3 新版 | 开源免费图床工具
javascript·笔记·electron
裕晟资质规划3 小时前
三类涉密资质延续时限差异分析:军工60日与集成印制3个月的边界
java·服务器·前端·网络·安全
ShineWinsu3 小时前
对于JavaScript:JavaScript基础语法的解析
开发语言·前端·javascript·面试·web·基础语法·循环
月夏3 小时前
Vue3 转 React:18 项对照表 + 5 个必踩的坑(附 7 天上手路线)
前端
广州华水科技3 小时前
单北斗GNSS位移监测系统的应用与维护解析
前端
fbincon3 小时前
Claude Code 自定义状态栏工具:安装、配置与 Subagent 状态展示
python·typescript·claude·claude-code·statusline