赞
踩
在网上找了好多代码,总是会有各种问题,成功只能靠自己呀
<template> <div> <el-tree :data="treeData" :props="treeProps" :default-expand-all="true" :render-content="renderContent" ></el-tree> </div> </template> <script> export default { data() { return { treeData: [ { id: 1, label: "Node 1", children: [ { id: 2, label: "Node 1-1", }, { id: 3, label: "Node 1-2", }, ], }, { id: 4, label: "Node 2", }, ], treeProps: { children: "children", label: "label", }, }; }, methods: { renderContent(h, { node, data }) { return ( <span class="custom-node"> {node.label} <span class="node-actions"> <el-button type="text" icon="el-icon-plus" onClick={() => this.addNode(data)} ></el-button> <el-button type="text" icon="el-icon-edit" onClick={() => this.editNode(data)} ></el-button> <el-button type="text" icon="el-icon-delete" onClick={() => this.deleteNode(data)} ></el-button> </span> </span> ); }, addNode(nodeData) { const newNode = { id: Date.now(), label: "New Node", }; if (!nodeData.children) { this.$set(nodeData, "children", []); } nodeData.children.push(newNode); }, editNode(nodeData) { this.$prompt("Enter new label", "Edit Node", { inputValue: nodeData.label, confirmButtonText: "Save", cancelButtonText: "Cancel", }) .then(({ value }) => { nodeData.label = value; }) .catch(() => {}); }, deleteNode(nodeData) { this.$confirm("Are you sure to delete this node?", "Delete Node", { confirmButtonText: "Delete", cancelButtonText: "Cancel", type: "warning", }) .then(() => { const parent = this.findParent(this.treeData, nodeData.id); parent.children = parent.children.filter( (child) => child.id !== nodeData.id ); }) .catch(() => {}); }, findParent(tree, nodeId) { for (let node of tree) { if (node.children) { if (node.children.some((child) => child.id === nodeId)) { return node; } else { const parent = this.findParent(node.children, nodeId); if (parent) { return parent; } } } } return null; }, }, }; </script> <style scoped> .custom-node { display: flex; align-items: center; } .node-actions { margin-left: auto; } </style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。