一.不选中父节点
回显数据需要在el-tree组件添加default-checked-keys属性
<template><div><el-button type="primary" @click="handleShowData">回显数据</el-button><el-tree :props="{ children: 'children', label: 'name' }" :data="treeList" show-checkbox node-key="id"@check="checkTree" ref="treeRef" :default-checked-keys="checkedKeysArr" /></div>
</template><script lang="ts">
import { toRefs, reactive, defineComponent, getCurrentInstance, nextTick } from 'vue';
export default defineComponent({setup() {const { proxy }: any = getCurrentInstance();const data = reactive({treeList: [{"id": 1,"name": "一级","pid": 0,"children": [{"id": 68,"name": "二级1","pid": 1,"children": [{"id": 71,"name": "三级1","pid": 68,},{"id": 72,"name": "三级2","pid": 68,}]},{"id": 69,"name": "二级2","pid": 1,"children": []},{"id": 70,"name": "二级3","pid": 1,"children": []}]}],checkedKeysArr: [] as number[],});const checkTree = (curObj: any, objArr: any,) => {console.log("objArr.checkedKeys--", objArr.checkedKeys);data.checkedKeysArr = objArr.checkedKeys}const handleShowData = () => {data.checkedKeysArr = [69, 70]}return {...toRefs(data), checkTree, handleShowData};},
});
</script>
二.选中父节点
1.需要手动回显数据,在el-tree组件移除default-checked-keys属性。
2.当子节点未全部选中时,父节点为半选中状态,将选中的节点数组和半选中的节点数组组合。
const checkTree = () => {let treeDom = proxy.$refs.treeRef;let array = treeDom.getCheckedKeys().concat(treeDom.getHalfCheckedKeys())console.log("array==", array);data.checkedKeysArr = array
}
3.开启父节点半选中需要添加手动回显数据
const handleShowData = () => {let defaultCheckArr = [69, 70, 1]let treeDom = proxy.$refs.treeRefnextTick(() => {defaultCheckArr?.forEach((v: number) => {treeDom.setChecked(v, true, false)})// 选中的数据const checkedNodes = treeDom.getCheckedNodes()console.log("checkedNodes==", checkedNodes);// 选中的namelet checkedName = checkedNodes.map((node: any) => node.name);console.log("checkedName==", checkedName);})
}