vue3渲染el-tree组件,给默认选中的节点,禁用所有子节点
实现逻辑:给默认选中节点的所有子节点添加一个disabled属性,以此禁用子节点。
编写代码
<template>
<el-tree :props="{ children: 'children', label: 'name' }" :data="treeListData" show-checkbox node-key="id" ref="treeRef"
check-strictly :default-expand-all="true" :default-checked-keys="checkedIdArr" @check-change="handleCheckChange" />
</template>
<script lang="ts">
import { toRefs, reactive, onMounted, defineComponent, getCurrentInstance } from 'vue';
export default defineComponent({
setup() {
// 页面加载时
onMounted(() => {
data.treeListData = setSubDisabled(data.treeListData, data.checkedIdArr)
});
const { proxy }: any = getCurrentInstance();
const data = reactive({
treeListData: [
{
id: 1,
name: "一级1",
pid: 0,
is_level: 1,
children: [
{
id: 2,
name: "二级1",
pid: 1,
is_level: 2,
children: [
{
id: 9,
name: "三级1",
pid: 1,
is_level: 3,
}
]
}
]
},
{
id: 3,
name: "一级2",
pid: 0,
is_level: 1,
children: [
{
id: 4,
name: "二级1",
pid: 3,
is_level: 2,
children: [
{
id: 5,
name: "三级1",
pid: 4,
is_level: 3,
children: [
{
id: 6,
name: "四级1",
pid: 5,
is_level: 4,
children: [
{
id: 7,
name: "五级1",
pid: 6,
is_level: 5,
}
]
}
]
}
]
},
{
id: 8,
name: "二级2",
pid: 3,
is_level: 2,
}
]
},
] as any[],
checkedIdArr: [1, 4]
});
function setSubDisabled(nodes: any[], checkedIdArr: number[]) {
nodes.forEach((node: any) => {
if (checkedIdArr.includes(node.id)) {
function setDisabled(sonNode: any[]) {
sonNode && sonNode.forEach((v: any) => {
v.disabled = true
if (v.children && v.children.length > 0) {
setDisabled(v.children)
}
})
}
setDisabled(node.children)
}
if (node.children && node.children.length > 0) {
setSubDisabled(node.children, checkedIdArr);
}
})
return nodes
}
const handleCheckChange = (curObj: any, checked: boolean,) => {
let getCheckedKeys = proxy.$refs.treeRef.getCheckedKeys()
let newArr = disableSubNodes(curObj.children, checked, getCheckedKeys)
data.checkedIdArr = newArr
proxy.$refs.treeRef.setCheckedKeys(newArr)
}
const disableSubNodes = (nodes: any, checked: boolean, checkedKeys: number[]) => {
nodes?.length > 0 && nodes.forEach((node: any) => {
checkedKeys = checkedKeys.filter((v: number) => v !== node.id)
node.disabled = checked;
if (node.children && node.children.length > 0) {
disableSubNodes(node.children, checked, checkedKeys);
}
});
return checkedKeys
}
return {
...toRefs(data), handleCheckChange
};
},
});
</script>
效果图