eltree增删改功能记录
程序员文章站
2024-03-24 09:28:46
...
需实现功能:
- 添加同级节点
- 添加子级节点
- 重命名节点
- 删除节点
HTML
<el-tree ref="tree" :data="data" node-key="id" default-expand-all draggable>
<div class="tree-node" slot-scope="{ node, data }">
<div class="tree-node">
<span v-if="data.label&&!node.checked" class="node-tit">{{ data.label }}</span>
<div v-else>
<el-input v-model="data.label"></el-input>
<el-button @click="saveLable(node, data)" class="save-btn">保存</el-button>
</div>
<span>
<el-dropdown>
<span class="el-dropdown-link">
<i class="el-icon-more"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item @click.native="() => insertAfter(node, data)">添加同级章节</el-dropdown-item>
<el-dropdown-item @click.native="() => append(node,data)">添加子级章节</el-dropdown-item>
<el-dropdown-item @click.native="() => nodeClick(node)">重命名</el-dropdown-item>
<el-dropdown-item @click.native="() => remove(node, data) ">删除</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</span>
</div>
</div>
</el-tree>
javascript
//添加同级节点
insertAfter(node, data) {
const nodeList = node.parent.childNodes;
const curArr = node.parent.data.children || node.parent.data;
const index = curArr.findIndex(d => d.id === data.id) + 1;
console.log(node);
new Promise((resolve, reject) => {
const newBrother = { id: ++this.id, label: "", children: [] };
curArr.splice(index, 0, newBrother);
resolve();
}).then(res => {
console.log(nodeList[index]);
nodeList[index].checked = true;
});
},
//添加子节点
append(node, data) {
const nodeList = node.childNodes;
console.log(nodeList);
new Promise((resolve, reject) => {
const newChild = { id: ++this.id, label: "", children: [] };
if (!data.children) {
this.$set(data, "children", []);
}
data.children.push(newChild);
resolve();
}).then(res => {
nodeList[nodeList.length - 1].checked = true;
});
},
//获取当前节点修改checked值
nodeClick(node) {
node.checked = true;
},
//删除节点
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);
},
//保存label
saveLable(node) {
node.checked = false;
},
推荐阅读