實現帶有進度條的Vue延遲載入

2020-10-28 18:00:29
下面給大家介紹一下給Vue的惰性載入新增進度條的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有所幫助。

簡介

通常用 Vue.js 編寫單頁應用(SPA)時,當載入頁面時,所有必需的資源(如 JavaScript 和 CSS 檔案)都會被一起載入。在處理大檔案時,這可能會導致使用者體驗不佳。

藉助 Webpack,可以用 import() 函數而不是 import 關鍵字在 Vue.js 中按需載入頁面。

為什麼要按需載入?

Vue.js 中 SPA 的典型工作方式是將所有功能和資源打包一併交付,這樣可以使使用者無需重新整理頁面即可使用你的應用。如果你沒有為了按需載入頁面針對自己的應用進行明確的設計,那麼所有的頁面會被立即載入,或者提前使用大量記憶體進行不必要的預載入。

這對有許多頁面的大型 SPA 非常不利,會導致使用低端手機和低網速的使用者體驗會很差。如果通過按需載入,使用者將不需要下載他們當前不需要的資源。

Vue.js 沒有為動態模組提供任何載入指示器相關的控制元件。即使進行了預取和預載入,也沒有對應的空間讓使用者知道載入的過程,所以還需要通過新增進度條來改善使用者體驗。

準備專案

首先需要一種讓進度條與 Vue Router 通訊的方法。事件匯流排模式比較合適。

事件匯流排是一個 Vue 範例的單例。由於所有 Vue 範例都有一個使用 $on$emit 的事件系統,因此可以用它在應用中的任何地方傳遞事件。

首先在 components 目錄中建立一個新檔案 eventHub.js

import Vue from 'vue'
export default new Vue()

然後把 Webpack 設定為禁用預取和預載入,這樣就可以針對每個函數單獨執行此類操作,當然你也可以全域性禁用它。在根資料夾中建立一個 vue.config.js 檔案並新增禁用預取和預載入的相關設定:

module.exports = {
    chainWebpack: (config) => {
        // 禁用預取和預載入
        config.plugins.delete('prefetch')
        config.plugins.delete('preload')
    },
}

新增路由和頁面

npx 安裝 Vue router 並使用:

$ npx vue add router

編輯位於 router/index.js 下的 router 檔案並更新路由,以便可以用 import() 函數代替 import 語句:

以下預設設定:

import About from '../views/About.vue'
{
    path: '/about',
    name: 'About',
    component: About
},

將其改為:

{
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
},

如果希望可以選擇按需載入某些頁面,而不是全域性禁用預取和預載入,可以用特殊的 Webpack 註釋,不要在 vue.config.js 中設定 Webpack:

import(
    /* webpackPrefetch: true */
    /* webpackPreload: true */
    '../views/About.vue'
)

import()import 之間的主要區別是在執行時載入由 import() 載入的 ES 模組,在編譯時載入由 import 載入的 ES 模組。這就意味著可以用 import() 延遲模組的載入,並僅在必要時載入。

實現進度條

由於無法準確估算頁面的載入時間(或完全載入),因此我們無法真正的去建立進度條。也沒有辦法檢查頁面已經載入了多少。不過可以建立一個進度條,並使它在頁面載入時完成。

由於不能真正反映進度,所以描繪的進度只是進行了隨機跳躍。

先安裝 lodash.random,因為在生成進度條的過程中將會用這個包產生一些亂數:

$ npm i lodash.random

然後,建立一個 Vue 元件 components/ProgressBar.vue

<template>
    <p :class="{'loading-container': true, loading: isLoading, visible: isVisible}">
        <p class="loader" :style="{ width: progress + '%' }">
            <p class="light"></p>
        </p>
        <p class="glow"></p>
    </p>
</template>

接下來向該元件新增指令碼。在指令碼中先匯入 random$eventHub,後面會用到:

<script>
import random from 'lodash.random'
import $eventHub from '../components/eventHub'
</script>

匯入之後,在指令碼中定義一些後面要用到的變數:

// 假設載入將在此時間內完成。
const defaultDuration = 8000 
// 更新頻率
const defaultInterval = 1000 
// 取值範圍 0 - 1. 每個時間間隔進度增長多少
const variation = 0.5 
// 0 - 100. 進度條應該從多少開始。
const startingPoint = 0 
// 限制進度條到達載入完成之前的距離
const endingPoint = 90

然後編碼實現非同步載入元件的邏輯:

export default {
    name: 'ProgressBar',
    
    data: () => ({
        isLoading: true, // 載入完成後,開始逐漸消失
        isVisible: false, // 完成動畫後,設定 display: none
        progress: startingPoint,
        timeoutId: undefined,
    }),

    mounted() {
        $eventHub.$on('asyncComponentLoading', this.start)
        $eventHub.$on('asyncComponentLoaded', this.stop)
    },

    methods: {
        start() {
            this.isLoading = true
            this.isVisible = true
            this.progress = startingPoint
            this.loop()
        },

        loop() {
            if (this.timeoutId) {
                clearTimeout(this.timeoutId)
            }
            if (this.progress >= endingPoint) {
                return
            }
            const size = (endingPoint - startingPoint) / (defaultDuration / defaultInterval)
            const p = Math.round(this.progress + random(size * (1 - variation), size * (1 + variation)))
            this.progress = Math.min(p, endingPoint)
            this.timeoutId = setTimeout(
                this.loop,
                random(defaultInterval * (1 - variation), defaultInterval * (1 + variation))
            )
        },

        stop() {
            this.isLoading = false
            this.progress = 100
            clearTimeout(this.timeoutId)
            const self = this
            setTimeout(() => {
                if (!self.isLoading) {
                    self.isVisible = false
                }
            }, 200)
        },
    },
}

mounted() 函數中,用事件匯流排來偵聽非同步元件的載入。一旦路由告訴我們已經導航到尚未載入的頁面,它將會開始載入動畫。

最後其新增一些樣式:

<style scoped>
.loading-container {
    font-size: 0;
    position: fixed;
    top: 0;
    left: 0;
    height: 5px;
    width: 100%;
    opacity: 0;
    display: none;
    z-index: 100;
    transition: opacity 200;
}

.loading-container.visible {
    display: block;
}
.loading-container.loading {
    opacity: 1;
}

.loader {
    background: #23d6d6;
    display: inline-block;
    height: 100%;
    width: 50%;
    overflow: hidden;
    border-radius: 0 0 5px 0;
    transition: 200 width ease-out;
}

.loader > .light {
    float: right;
    height: 100%;
    width: 20%;
    background-image: linear-gradient(to right, #23d6d6, #29ffff, #23d6d6);
    animation: loading-animation 2s ease-in infinite;
}

.glow {
    display: inline-block;
    height: 100%;
    width: 30px;
    margin-left: -30px;
    border-radius: 0 0 5px 0;
    box-shadow: 0 0 10px #23d6d6;
}

@keyframes loading-animation {
    0% {
        margin-right: 100%;
    }
    50% {
        margin-right: 100%;
    }
    100% {
        margin-right: -10%;
    }
}
</style>

最後將 ProgressBar 新增到 App.vue 或佈局元件中,只要它與路由檢視位於同一元件中即可,它在應用的整個生命週期中都可用:

<template>
    <p>
        <progress-bar></progress-bar>
        <router-view></router-view>
        <!--- 你的其它元件 -->
    </p>
</template>

<script>
import ProgressBar from './components/ProgressBar.vue'
export default {
       components: { ProgressBar },
}
</script>

然後你就可以在頁面頂端看到一個流暢的進度條:

1.png

為延遲載入觸發進度條

現在 ProgressBar 正在事件匯流排上偵聽非同步元件載入事件。當某些資源以這種方式載入時應該觸發動畫。現在向路由新增一個路由守護來接收以下事件:

import $eventHub from '../components/eventHub'

router.beforeEach((to, from, next) => {
    if (typeof to.matched[0]?.components.default === 'function') {
        $eventHub.$emit('asyncComponentLoading', to) // 啟動進度條
    }
    next()
})

router.beforeResolve((to, from, next) => {
    $eventHub.$emit('asyncComponentLoaded') // 停止進度條
    next()
})

為了檢測頁面是否被延遲載入了,需要檢查元件是不是被定義為動態匯入的,也就是應該為 component:() => import('...') 而不是component:MyComponent

這是通過 typeof to.matched[0]?.components.default === 'function' 完成的。帶有 import 語句的元件不會被歸為函數。

總結

在本文中,我們禁用了在 Vue 應用中的預取和預載入功能,並建立了一個進度條元件,該元件可顯示以模擬載入頁面時的實際進度。

原文:https://stackabuse.com/lazy-loading-routes-with-vue-router/

作者:Stack Abuse

相關推薦:

更多程式設計相關知識,請存取:!!

以上就是實現帶有進度條的Vue延遲載入的詳細內容,更多請關注TW511.COM其它相關文章!