使用js计时器,延迟执行,当符合某个条件时,在进行渲染组件,避免一次性渲染太多内容造成白屏
useDefer.js
import {
ref
} from "vue";
function useDefer(maxFrameCount = 1000) {
const frameCount = ref(0);
const refershFrameCount = () => {
requestAnimationFrame(() => {
frameCount.value++;
if (frameCount.value < maxFrameCount) {
refershFrameCount();
}
})
}
refershFrameCount();
return (showInFrameCount) => {
return frameCount.value >= showInFrameCount
}
}
export default useDefer
使用
<template>
<div class="home-wrap">
<template v-for="item in 100" :key="item">
<mz-item-line :count="item" v-if="defer(item)"></mz-item-line>
</template>
</div>
</template>
<script setup>
import mzItemLine from '@/components/mz-item-line.vue';
import useDefer from '@/utils/useDefer.js';
const defer = useDefer(101);
</script>
<style lang="scss" scoped>
.home-wrap {
border: 1px solid red;
max-width: 1200px;
margin: auto;
display: flex;
flex-wrap: wrap;
}
</style>