关于element中的el-tree和el-tag之间的联动,意思就是你在el-tree上选择一个选项,那么在el-tag中就会多一个选项,你如果取消一个选项,那么在el-tag中也会少一个对应的选项,还有就是你在el-tag中点击删除一个选项,那么在el-tree中所对应的选项也要取消勾选。话不多说,下面上代码
<template>
<div>
<el-tree
ref="tree"
class="tenant_tree"
:data="data"
show-checkbox
:props="defaultProps"
node-key="id"
highlight-current
@check-change="handleCheckChange"
></el-tree>
<el-tag
v-for="(tag, index) in tags"
:key="index"
style="margin: 10px 10px"
closable
@close="handleClose(tag)"
>
{{ tag.label }}
</el-tag>
</div>
</template>
<script>
const data = [
{
id: 1,
label: "Level one 1",
children: [
{
id: 3,
label: "Level two 2-1",
children: [
{
id: 4,
label: "Level three 3-1-1",
},
{
id: 5,
label: "Level three 3-1-2",
},
{
id: 8,
label: "Level three 3-1-3",
},
{
id: 9,
label: "Level three 3-1-4",
},
],
},
{
id: 2,
label: "Level two 2-2",
children: [
{
id: 6,
label: "Level three 3-2-1",
},
{
id: 7,
label: "Level three 3-2-2",
},
{
id: 10,
label: "Level three 3-2-3",
},
{
id: 11,
label: "Level three 3-2-4",
},
],
},
],
},
{
id: 12,
label: "Level one 2",
children: [
{
id: 13,
label: "Level two 2-3",
children: [
{
id: 14,
label: "Level three 3-3-1",
},
{
id: 15,
label: "Level three 3-3-2",
},
{
id: 16,
label: "Level three 3-3-3",
},
],
},
{
id: 17,
label: "Level two 2-4",
children: [
{
id: 18,
label: "Level three 3-4-1",
},
{
id: 19,
label: "Level three 3-4-2",
},
{
id: 20,
label: "Level three 3-4-3",
},
],
},
],
},
];
export default {
data() {
return {
searchData: "",
data: [],
defaultProps: {
children: "children",
label: "label",
},
tags: [], // 选中的节点,
checked: false,
};
},
mounted() {
this.data = data;
},
methods: {
handleCheckChange() {
this.tags = this.$refs.tree.getCheckedNodes();
console.log("总的数据是", this.tags);
},
// 标签删除事件
handleClose(tag) {
console.log("所点击的是", tag);
console.log("总的数据是", this.tags);
for (let i = 0; i < this.tags.length; i++) {
const element = this.tags[i];
if (tag.id === element.id) {
this.tags.splice(i, 1);
this.$refs.tree.setChecked(tag.id, null);
}
}
},
},
};
</script>
实现的效果如下图所示:
我点击下面的el-tag的3-4-2和3-4-3后面的关闭,则会出现如下图的情况
代码在上面,你们需要的可以复制去试试,当然前提是你的项目上要有element组件,不过这里会有一个问题,就是你如果点击el-tag下面的树形数据的第一个选项的时候,他会变成空的,而下面的子节点却没有清空,这种情况要另外再做处理,以上就是有关于element中的el-tree和el-tag之间的联动,代码还需进步,我也还需要进步,望各位大佬,轻点喷。