[Vue] useDefer to improve the rendering performacne

Zhentiw發表於2024-11-28

Let's say on the page we have some heavy component need to be render when page load.

<template>
    <div class="container">
        <div v-for="n in 100">
            <heavy-comp></heavy-comp>
        </div>
    </div>
</template>

<script setup>
    import HeavyComp from './componennts/HeavyComp.vue';
</script>

When everything need to be render at the same time, browser need more time to do the job, therefore users will feel slowness.

Idea is to render few components first, then rest components will be rendered when browser can.

<template>
    <div class="container">
        <div v-for="n in 100">
            <heavy-comp v-if="defer(n)"></heavy-comp>
        </div>
    </div>
</template>

<script setup>
    import HeavyComp from './componennts/HeavyComp.vue';
    import useDefer from './use/defer.js';
    
    const defer = useDefer()
</script>
import {ref} from "vue"

export default function useDefer() {
    const count = ref(0)
    function update() {
        count.value++
        requestAnimationFrame(update);
    }
    update()
    return function (n) {
        return count.value >= n;
    }
}

相關文章