Elment Plus版本
2.8.8
使用场景
接口返回叶子节点选中状态,组件计算渲染树选中状态缓慢
代码示例
<template>
<el-tree-v2
ref="treeRef"
:data="treeData"
show-checkbox
>
</template>
<script setup>
import { onMounted, ref } from "vue";
const treeRef = ref(/*树型组件引用对象*/);
const treeData = ref([/*...树节点数据*/]);
onMounted(async () => {
treeData.value = [/*假设从接口返回数据*/];
// 选中的叶子节点(必须用对象包裹)
const checkedLeafNodes = { nodes: [/*假设从接口返回数据*/] };
// 选中的节点(最终结果)
const checkedNodes = { nodes: [] };
// 遍历所有根节点,并将结果输出到 checkedNodes 中
for (let node of treeData.value) {
mergeTreeCheckedNodes(node, checkedNodes, accessibleDirectories);
}
treeRef.value.setCheckedKeys(checkedNodes.nodes);
});
// 合并选中的节点
const mergeTreeCheckedNodes = (node, input, output) => {
if (node.children.length === 0) {
const index = input.indexOf(node.id);
if (index !== -1) {
output.nodes.push(node.id);
return true;
}
return false;
} else {
let result = true;
for (const childNode of node.children) {
if (!mergeTreeCheckedKeys(childNode, input, output)) {
result = false;
}
}
if (result) {
const childNodeIds = node.children.map((item) => item.id);
output.nodes = output.nodes.filter(
(nodeId) => !childNodeIds.includes(nodeId)
);
output.nodes.push(node.id);
}
return result;
}
};
</script>
结果
我自己试了下,数据量大的时候速度快很多,有更好的逻辑可以放评论区大家一起讨论