由于element ui官方文档中,自定义树并没有编辑这个功能。只有添加和删除。由于需要一个添加课程章节的功能,然后找了好多人询问,最后终于勉强捣鼓出来。
在原element ui 自定义树的基础上加了添加子节点可重命名和编辑节点内容的功能,方便和我一样的前端小白还想用一些奇怪特效的人。因为我没学过vue,所以是用html文件运行的。可以直接复制到一个html文件里运行看看效果。代码排版有点乱,因为改的时候手忙脚乱的。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<style>
.custom-tree-node {
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
padding-right: 8px;
}
</style>
<body>
<div id="app">
<div class="custom-tree-container">
<div class="block">
<el-tree
:data="data"
node-key="id"
default-expand-all
:expand-on-click-node="false">
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button
type="text"
size="mini"
@click="() => append(data)">
添加
</el-button>
<el-button
type="text"
size="mini"
@click="() => remove(node, data)">
删除
</el-button>
<el-button
type="text"
size="mini"
@click="() => open(node, data)">
编辑
</el-button>
</span>
</span>
</el-tree>
</div>
</div>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
let id = 1000;
var Main = {
data() {
const data = [{
id: 0,
label: '点击展开章节列表',
children: [{
id: 1,
label: '第1章',
}]
}];
return {
data: JSON.parse(JSON.stringify(data)),
data: JSON.parse(JSON.stringify(data))
}
},
methods: {
open(node, data) {
this.$prompt('请输入章节名称', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
}).then(({ value }) => {
console.log(data);
data.label = value
this.$message({
type: 'success',
message: '你输入的章节名称是: ' + value,
});
}).catch(() => {
this.$message({
type: 'info',
message: '取消输入'
});
});
},
append(data) {
this.$prompt('请输入章节名称', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
}).then(({ value }) => {
console.log(data);
const newChild = { id: id++, label: value, children: [] };
if (!data.children) {
this.$set(data, 'children', []);
}
data.children.push(newChild);
this.$message({
type: 'success',
message: '你添加的章节名称是: ' + value,
});
}).catch(() => {
this.$message({
type: 'info',
message: '取消输入'
});
});
},
remove(node, data) {
// 判断该节点是否有子节点
if (node.childNodes.length != 0) {
this.$message({
message: '该节点下存在子节点,不允许直接删除',
type: 'warning'
});
return;
}
const parent = node.parent;
const children = parent.data.children || parent.data;
const index = children.findIndex(d => d.id === data.id);
children.splice(index, 1);
},
}
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
</script>
</html>