<template>
<div class="wrapper">
<a-tree v-model="checkedKeys" checkable defaultExpandAll @check="onCheck" :tree-data="treeData" />
<div>
<a-tag v-for="(tag,index) in tags" :key="tag.key" closable v-if="tag.isShow" @close="handleClose(tag.key,index)">
{{tag.title}}
</a-tag>
</div>
</div>
</template>
<script>
const treeData = [
{
title: '0-0',
key: '0-0',
children: [
{
title: '0-0-0',
key: '0-0-0',
children: [
{ title: '0-0-0-0', key: '0-0-0-0' },
{ title: '0-0-0-1', key: '0-0-0-1' },
{ title: '0-0-0-2', key: '0-0-0-2' },
],
},
{
title: '0-0-1',
key: '0-0-1',
children: [
{ title: '0-0-1-0', key: '0-0-1-0' },
{ title: '0-0-1-1', key: '0-0-1-1' },
{ title: '0-0-1-2', key: '0-0-1-2' },
],
},
{
title: '0-0-2',
key: '0-0-2',
},
],
},
{
title: '0-1',
key: '0-1',
children: [
{ title: '0-1-0-0', key: '0-1-0-0' },
{ title: '0-1-0-1', key: '0-1-0-1' },
{ title: '0-1-0-2', key: '0-1-0-2' },
],
},
{
title: '0-2',
key: '0-2',
},
]
export default {
components: {},
data() {
return {
checkedKeys: ['0-0-0-1', '0-0-0-2'],// 选中数据
treeData,
tags: [], //菜单
}
},
mounted() {
// 初始化获取选中数据的title
this.getTagsData(this.treeData, this.tags)
},
methods: {
// 复选框事件
onCheck(checkedKeys, e) {
this.checkedKeys = checkedKeys
this.tags = []
e.checkedNodes.map((item) => {
this.tags.push({
key: item.key,
title: item.data.props.title,
isShow: item.data.props.dataRef.children ? false : true, // 有子级的父级不显示
})
})
},
// 菜单删除事件
handleClose(key, index) {
this.tags.splice(index, 1)
let result=[]
this.getParentId(key,this.treeData,result)
// 删除子级需获取父级id一同删除 否则父级选中状态依旧存在
result.map(item=>{
this.checkedKeys=this.checkedKeys.filter(its=>its!=item)
})
},
// 初始化数据处理 通过key 获取title
getTagsData(data, tags) {
data.map((item) => {
this.checkedKeys.map((its) => {
if (item.key === its) {
tags.push({
key: item.key,
title: item.title,
isShow: item.children && item.children.length > 0 ? false : true,
})
}
})
if (item.children) {
this.getTagsData(item.children, tags)
}
})
},
// 获取父级id
getParentId(id, list = [], result = []) {
for (let i = 0; i < list.length; i += 1) {
const item = list[i]
if (item.key === id) {
result.push(item.key)
if (result.length === 1) return result
return true
}
// 如果存在下级节点,则继续遍历
if (item.children) {
// 预设本次是需要的节点并加入到最终结果result中
result.push(item.key)
const find = this.getParentId(id, item.children, result)
// 如果不是false则表示找到了,直接return,结束递归
if (find) {
return result
}
// 到这里,意味着本次并不是需要的节点,则在result中移除
result.pop()
}
}
// 如果都走到这儿了,也就是本轮遍历children没找到,将此次标记为false
return false
}
},
}
</script>
<style lang='less' scoped>
.wrapper {
background: #fff;
padding: 10px;
}
</style>
antd vue tree 选中的菜单显示单独取消选中,tree取消子级选中 关联父级同时取消选中
最新推荐文章于 2024-01-18 17:04:47 发布