要实现的效果:
鼠标移入显示增删改按钮,根节点只允许新增。
<div> <el-tree :data="natureOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" node-key="id" ref="tree" default-expand-all @node-click="handleNodeClick" > <span class="custom-tree-node show-hide" slot-scope="{ node, data }"> <span>{{ node.label }}</span> <span style="display:none"> <i @click="() => appendNode(node, data)" class="el-icon-plus" title="增加"></i><!--增加节点--> <!-- 根节点不需要删除和修改 --> <i v-if="data.id !== 1" @click="() => removeNode(node,data)" class="el-icon-delete" title="删除"></i><!--删除节点--> <i v-if="data.id !== 1" @click="() => editNode(node,data)" class="el-icon-edit" title="编辑"></i><!--编辑节点--> </span> </span> </el-tree> </div>
.custom-tree-node { flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px; } .show-hide:hover :nth-child(2) { display: inline-block !important; }
然后就是实现这几个增删改的方法:
// 新增树节点 appendNode(node, data) { this.resetNodeForm(); this.nodeForm.parentId = data.id; getNatureTreeNode().then(response =>{ if(response.code === 200){ this.nodeTitle = "添加节点"; this.parentTreeName = data.label; this.dialogNodeFormVisible = true; } }); }, // 删除树节点 removeNode(node, data) { // 判断该节点是否有子节点 if(node.childNodes.length != 0){ this.$message({ message: '该节点下存在子节点,不允许直接删除', type: 'warning' }); return; } this.$confirm("是否确认删除此节点?", "警告", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning", }) .then(function () { return delNatureTreeNode(data.id); }) .then(response => { if (response.code === 200){ this.getTreeselect(); this.msgSuccess("删除成功"); } else { this.$message({ message: response.msg, type: 'warning' }); return; } }) .catch(function () {}); }, // 编辑树节点 editNode(node, data) { this.resetNodeForm(); getNatureTreeNode(data.id).then(response =>{ if(response.code === 200){ this.nodeForm = response.data; this.nodeTitle = "编辑节点"; this.parentTreeName = node.parent.label; this.dialogNodeFormVisible = true; } }); }