溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue 中怎么惰性加載加一個進度條

發(fā)布時間:2021-07-09 11:11:07 來源:億速云 閱讀:181 作者:Leah 欄目:web開發(fā)

本篇文章為大家展示了Vue 中怎么惰性加載加一個進度條,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

為什么要按需加載?

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

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

Vue.js  沒有為動態(tài)模塊提供任何加載指示器相關的控件。即使進行了預取和預加載,也沒有對應的空間讓用戶知道加載的過程,所以還需要通過添加進度條來改善用戶體驗。

準備項目

首先需要一種讓進度條與 Vue Router 通信的方法。事件總線模式比較合適。

事件總線是一個 Vue 實例的單例。由于所有 Vue 實例都有一個使用 $on和 $emit的事件系統,因此可以用它在應用中的任何地方傳遞事件。

首先在 components 目錄中創(chuàng)建一個新文件 eventHub.js:

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

然后把 Webpack 配置為禁用預取和預加載,這樣就可以針對每個函數單獨執(zhí)行此類操作,當然你也可以全局禁用它。在根文件夾中創(chuàng)建一個  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 之間的主要區(qū)別是在運行時加載由 import() 加載的 ES 模塊,在編譯時加載由 import 加載的 ES  模塊。這就意味著可以用 import() 延遲模塊的加載,并僅在必要時加載。

實現進度條

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

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

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

$ npm i lodash.random

然后,創(chuàng)建一個 Vue 組件 components/ProgressBar.vue:

<template>     <div :class="{'loading-container': true, loading: isLoading, visible: isVisible}">         <div class="loader" :style="{ width: progress + '%' }">             <div class="light"></div>         </div>         <div class="glow"></div>     </div> </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>     <div>         <progress-bar></progress-bar>         <router-view></router-view>         <!--- 你的其它組件 -->     </div> </template>  <script> import ProgressBar from './components/ProgressBar.vue' export default {        components: { ProgressBar }, } </script>

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

Vue 中怎么惰性加載加一個進度條

頁面頂端的進度條

為延遲加載觸發(fā)進度條現在 ProgressBar  正在事件總線上偵聽異步組件加載事件。當某些資源以這種方式加載時應該觸發(fā)動畫?,F在向路由添加一個路由守護來接收以下事件:

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() })

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

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

上述內容就是Vue 中怎么惰性加載加一個進度條,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

vue
AI