前提:最近有个树形需求,勾选父级自动勾选子集,勾选子集不关联父级
我的第一反应就是check-strictly设为true不关联,用父级唯一标识去判断是不是父级,然后利用check方法把下面所有符合父级要求的值丢到setCheckedKeys中,但这个有两个问题如果有两个数据,只能勾选一个,点击子集也无法勾选,可能需要自己去适配吧
想到另外一种思路利用check-change方法判断是不是勾选状态,是的话就遍历子集
<script setup>
import {
reactive,
ref
} from 'vue';
const defaultProps = ref({
label: "packageName",
children: "childrens",
})
const tree = ref()
const handleCheckChange = (node, checked) => {
//全部取消/选择
const setChecked = (arr, ifChecked) => {
arr?.map((item) => {
tree.value.setChecked(item.id, ifChecked);
if (!!item?.childrens?.length) {
setChecked(item?.childrens, ifChecked);
}
});
};
//如果为取消
if (checked === false) {
//如果当前节点有子集
//循环子集将他们的选中取消
//修复子父级勾选子集勾选问题
if (node.packageType === "First") {
setChecked(node?.childrens ?? [], false);
}
} else {
//否则(为选中状态)
//判断父节点packageType 是否为First
if (node.packageType === "First") {
//如果父级就勾选所有子集
setChecked(node?.childrens ?? [], true);
}
}
}
const checkTree = ()=>{
}
const nodeclick = () =>{
console.log('点击后处理');
}
const treeData = reactive([{
"id": "1",
"packageType": "First",
"packageName": "一层(1)",
"childrens": [{
"id": "12",
"packageType": "一层(1-1)",
"packageName": "黄金精品",
"childrens": [{
"id": "122",
"packageType": "一层(1-2)",
"packageName": "一口价",
"childrens": []
}]
},
{
"id": "13",
"packageType": "一层(2-1)",
"packageName": "古法饰品",
"childrens": [{
"id": "131",
"packageType": "一层(2-2)",
"packageName": "工费3",
"childrens": []
}]
}
]
},
{
"id": "2",
"packageType": "First",
"packageName": "金仓",
"childrens": [{
"id": "21",
"packageType": "二层(2-3)",
"packageName": "黄金精品",
"childrens": [{
"id": "22",
"packageType": "COST",
"packageName": "工费",
"childrens": []
},
{
"id": "23",
"packageType": "二层(2-4)",
"packageName": "一口价",
"childrens": []
}
]
}]
}
])
</script>
<template>
<div class="app">
<el-tree node-key="id" ref="tree" :data="treeData" :props="defaultProps" @check-change="handleCheckChange"
@node-click="nodeclick" show-checkbox @check="checkTree" :check-strictly="true" default-expand-all="true">
</el-tree>
</div>
</template>
<style scoped>
.app{
display: flex;
width: 100vw;
height: 100vh;
background-color: #fff;
}
</style>
2024/3/23 修复了下面子父集勾选下面子集也勾选的问题