Vue写一个树形组件,并且可以新增、删除、编辑节点
时间: 2024-01-14 12:02:15 浏览: 111
好的,下面是一个简单的 Vue 树形组件,其中包括新增、删除、编辑节点功能:
```html
<template>
<div>
<ul>
<li v-for="(node, index) in nodes" :key="index">
<span @click="toggle(node)">
{{ node.name }}
</span>
<button @click="addChild(node)">新增子节点</button>
<button @click="editNode(node)">编辑</button>
<button @click="removeNode(node)">删除</button>
<tree :nodes="node.children" v-if="node.expanded" @add="addChild" @edit="editNode" @remove="removeNode"></tree>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "Tree",
props: {
nodes: {
type: Array,
required: true,
},
},
methods: {
toggle(node) {
node.expanded = !node.expanded;
},
addChild(parentNode) {
const newNode = {
name: "New Node",
children: [],
};
if (!parentNode.children) {
this.$set(parentNode, "children", []);
}
parentNode.children.push(newNode);
this.$emit("add", parentNode);
},
editNode(node) {
const newName = prompt("请输入新的节点名称", node.name);
if (newName !== null) {
node.name = newName;
this.$emit("edit", node);
}
},
removeNode(node) {
const parentNode = this.findParentNode(node);
if (parentNode) {
parentNode.children.splice(parentNode.children.indexOf(node), 1);
this.$emit("remove", parentNode);
} else {
this.nodes.splice(this.nodes.indexOf(node), 1);
this.$emit("remove", null);
}
},
findParentNode(node) {
for (const parentNode of this.nodes) {
if (parentNode.children && parentNode.children.includes(node)) {
return parentNode;
}
}
return null;
},
},
};
</script>
```
在父组件中,可以通过以下方式使用该组件:
```html
<template>
<div>
<tree :nodes="nodes" @add="onAdd" @edit="onEdit" @remove="onRemove"></tree>
</div>
</template>
<script>
import Tree from "./Tree.vue";
export default {
name: "App",
components: {
Tree,
},
data() {
return {
nodes: [
{
name: "Node 1",
children: [
{
name: "Node 1.1",
children: [
{
name: "Node 1.1.1",
},
{
name: "Node 1.1.2",
},
],
},
{
name: "Node 1.2",
},
],
},
{
name: "Node 2",
children: [
{
name: "Node 2.1",
},
{
name: "Node 2.2",
},
],
},
],
};
},
methods: {
onAdd(node) {
console.log("add node", node);
},
onEdit(node) {
console.log("edit node", node);
},
onRemove(node) {
console.log("remove node", node);
},
},
};
</script>
```
该树形组件会根据传入的 nodes 属性递归地渲染节点,并且对于每个节点,都提供了新增子节点、编辑节点和删除节点的按钮。当用户点击这些按钮时,会触发对应的事件,父组件可以在事件处理函数中更新 nodes 属性。这样,当用户新增、编辑或删除节点时,树形组件会自动重新渲染。
阅读全文