优化El-tree大量数据插入造成页面卡顿问题
背景
在一个已采用懒加载方式加载到特定层级的el-tree
组件中,现在需要向该层级下的某个节点动态加载并插入大量子数据,并将其渲染至DOM结构中。此时,页面直接无响应卡顿了5秒,经排查发现,是触发了大量Vue3中的instance.update方法。此时应该如何解决呢?
解决方案
分块处理:
将大任务拆分为小任务,每处理完一部分就暂停一下,让主线程有机会执行渲染和其他任务,比如使用Promise链式调用或Generator函数实现。
原先
data.forEach((item) => {
treeRef.value.append(
{
xxxx
},
node
);
});
新建insertNodesInBatches方法,按照分段插入的思想,定时插入数据,使得Vue不需要频繁地Patch,避免了浏览器巨大的计算压力。
优化后
await insertNodesInBatches(node, type, data);
async function insertNodesInBatches(node, type, data) {
const batchSize = 20; // 一次性插入条数
let currentIndex = 0;
while (currentIndex < data.length) {
const batchEndIndex = Math.min(currentIndex + batchSize, data.length);
const batchData = data.slice(currentIndex, batchEndIndex);
batchData.forEach((item) => {
treeRef.value.append(
{
...
},
node
);
});
currentIndex += batchSize;
// 可以在这儿添加一个短暂的延迟,避免过于频繁的UI更新
await new Promise(resolve => setTimeout(resolve, 200)); // 200毫秒插入一次
}
}