Vue2實現(xiàn)組件延遲加載的示例代碼
1.背景
當(dāng)一個頁面需要加載較多個組件時,并且組件自身又比較復(fù)雜。如果一次性加載,可能等待時間較長,體驗不好。
一種解決辦法:分批次的來渲染子組件。
2.實現(xiàn)
通過 requestAnimationFrame(callback) 實現(xiàn),同時能夠控制按照指定順序來渲染。
簡單理解為:瀏覽器會按照一定的頻率來重繪頁面,大概 60次/s。每次重繪前都會執(zhí)行 callback 函數(shù)。這樣的話,我們可以在每次重繪前都只渲染一個組件,來實現(xiàn)組件的延遲加載。
示例代碼:
2.1延遲加載的核心代碼
通過 mixin 來實現(xiàn)。大致邏輯:
首先會傳入一個最大重繪次數(shù)。
定義一個計數(shù)當(dāng)前重繪次數(shù)的變量,每次調(diào)用 callback 時自增,重繪次數(shù)達(dá)到最大則結(jié)束 requestAnimationFrame 的執(zhí)行。
定義一個方法,參數(shù)為指定的順序,返回值用于判斷組件是否展示。
比如 v-if="deferItem(5)" 表示瀏覽器第5次重繪時渲染該組件。
export default function defer(maxFrameCount) { return { data() { return { frameCount: 0, }; }, mounted() { const refreshFrame = () => { requestAnimationFrame(() => { this.frameCount++; if (this.frameCount < maxFrameCount) { refreshFrame(); } }); }; refreshFrame(); }, methods: { deferItem(showFrameCount) { return this.frameCount >= showFrameCount; }, }, }; }
2.2模擬的復(fù)雜組件
子組件內(nèi)部有 20000 個元素需要渲染,來模擬復(fù)雜的組件。
<template> <div class="container"> <div v-for="n in 20000" class="item"></div> </div> </template> <script></script> <style scoped> .container { display: flex; flex-wrap: wrap; align-items: center; width: 300px; height: 300px; } .item { width: 5px; height: 5px; background-color: #eee; margin: 0.1em; } </style>
2.3父組件
模擬渲染 25 個復(fù)雜子組件。
<template> <div class="container"> <div v-for="n in 25" :key="n" class="wrapper"> <HeavyComp v-if="deferItem(n)" /> </div> </div> </template> <script> import HeavyComp from "./components/HeavyComp.vue"; import defer from "./mixins/defer"; export default { components: { HeavyComp, }, mixins: [defer(25)], }; </script> <style scoped> .container { display: flex; flex-wrap: wrap; } .wrapper { border: 1px solid salmon; } </style>
3.效果
到此這篇關(guān)于Vue2實現(xiàn)組件延遲加載的示例代碼的文章就介紹到這了,更多相關(guān)Vue2組件延遲加載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue中的雙向數(shù)據(jù)綁定原理與常見操作技巧詳解
這篇文章主要介紹了vue中的雙向數(shù)據(jù)綁定原理與常見操作技巧,結(jié)合實例形式詳細(xì)分析了vue中雙向數(shù)據(jù)綁定的概念、原理、常見操作技巧與相關(guān)注意事項,需要的朋友可以參考下2020-03-03el-select 數(shù)據(jù)回顯,只顯示value不顯示lable問題
這篇文章主要介紹了el-select 數(shù)據(jù)回顯,只顯示value不顯示lable問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09解決element-ui table設(shè)置列fixed時X軸滾動條無法拖動問題
這篇文章主要介紹了解決element-ui table設(shè)置列fixed時X軸滾動條無法拖動問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10