vue2 、 vue3首屏优化,减少白屏时间

在第一帧的时候加载应该被用户看到的页面部分,剩下的逐步加载

1. 使用v-for来模拟页面有很多重组件

复制代码
<template v-for="item in 100">
            <sub-home-page :key="item" v-if="defer(item)"></sub-home-page>
        </template>

2.在created钩子中使用requestAnimationFrame对count进行赋值

复制代码
let that = this
        function updataFrame() {
            that.count++;
            if(that.count >= this.components) return 
            that.reqId = requestAnimationFrame(updataFrame);
        }
        updataFrame();

3.使用计算属性,来控制组件是否渲染

复制代码
defer(){
            return function(n){
                return this.count >= n;
            }
        }

4.在页面销毁的时候,取消requestAnimationFrame

复制代码
destroyed(){
        cancelAnimationFrame(that.reqId)
    },

Vue3版本:

首页模拟100个重组件

复制代码
<template>
    <div class="index">
        <div v-for="item in 100" :key="item">
            <sub-index v-if="defer(item)"></sub-index>
        </div>
    </div>
</template>

<script setup>
import subIndex from "./components/subIndex.vue";
import { useDefer } from "/src/utils/useDefer.js";
const defer = useDefer();
</script>

<style lang="less" scoped>
.index{
    width: 100%;
    height: 100%;
    overflow: auto;
    display: grid;
    grid-template-columns: repeat(3, fr);
    grid-gap: 0.1em;
}
</style>

子组件(重组件)

复制代码
<template>
    <div class="subHomePage">
        <div class="item" v-for="item in 5000" :key="item">
        </div>
    </div>
</template>

<script setup>

</script>
<style scoped lang="less">
.subHomePage{
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    border: 3px solid red;
    .item{
        width: 5px;
        height: 3px;
        background: #ccc;
        margin: 0.1em;
    }
}
</style>

useDefer.js文件

复制代码
import { ref, onUnmounted } from "vue";
export function useDefer(maxCount = 100){
    let count = ref(0);
    let reqId = null;
    function updataFrame() {
        count.value++;
        if(count.value >= maxCount) return 
        reqId = requestAnimationFrame(updataFrame);
    }
    updataFrame();

    onUnmounted(() => {
        cancelAnimationFrame(reqId)
    })

    return function (n){
        return count.value >= n;
    }
}
相关推荐
Mintopia2 分钟前
Three.js 自定义几何体:解锁 3D 世界的创造力
前端·javascript·three.js
Mintopia5 分钟前
计算机图形学碰撞检测:数字世界的 “防碰瓷” 秘籍
前端·javascript·计算机图形学
Hilaku7 分钟前
为什么说 CSS 是最被低估的编程语言?
前端·css
网硕互联的小客服7 分钟前
如何排查 Docker 容器资源占用过高的问题?
运维·服务器·网络·安全·docker·容器
阿蒙Amon11 分钟前
C#最佳实践:为何优先使用as或is而非强制转换
服务器·数据库·c#
Hilaku16 分钟前
我用 Cursor 写了两个月代码,项目代码量不降反升,为什么?
前端·javascript·架构
哀木16 分钟前
识别手写数字,居然可以只靠前端?
前端
Dream耀20 分钟前
掌握Flex布局核心:项目属性深度指南
前端·css·html
执笔为剑22 分钟前
Linux系统部署KES
linux·运维·服务器