Home > Web Front-end > Vue.js > body text

Implement Vue lazy loading with progress bar

青灯夜游
Release: 2020-10-28 17:36:32
forward
2659 people have browsed it

The followingVue.js column will introduce to you how to add a progress bar to Vue's lazy loading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Implement Vue lazy loading with progress bar

Introduction

Usually when writing a single page application (SPA) with Vue.js, when the page is loaded, all required resources (such as JavaScript and CSS files) will be loaded together. This can lead to a poor user experience when working with large files.

With Webpack, you can load pages on demand in Vue.js using the import() function instead of the import keyword.

Why load on demand?

The typical way SPA works in Vue.js is to package all functions and resources and deliver them together, so that users can use your application without refreshing the page. If you don't explicitly design your application to load pages on demand, all pages will be loaded at once, or a large amount of memory will be used in advance for unnecessary preloading.

This is very detrimental to large SPA with many pages, and will lead to poor user experience using low-end mobile phones and low network speeds. With on-demand loading, users won't need to download resources they don't currently need.

Vue.js does not provide any loading indicator related controls for dynamic modules. Even if prefetching and preloading are performed, there is no corresponding space to let the user know the loading process, so it is necessary to improve the user experience by adding a progress bar.

Preparing the project

First you need a way for the progress bar to communicate with Vue Router. Event bus mode is more suitable.

The event bus is a singleton of a Vue instance. Since all Vue instances have an event system using $on and $emit, you can use this to deliver events anywhere in your application.

First create a new file eventHub.js in the components directory:

import Vue from 'vue'
export default new Vue()
Copy after login

Then configure Webpack to disable prefetching and preloading, This allows you to do this on a per-function basis, or you can disable it globally. Create a vue.config.js file in the root folder and add the relevant configuration to disable prefetching and preloading:

module.exports = {
    chainWebpack: (config) => {
        // 禁用预取和预加载
        config.plugins.delete('prefetch')
        config.plugins.delete('preload')
    },
}
Copy after login

Add routes and pages

Use npx Install Vue router and use:

$ npx vue add router
Copy after login

Edit the router file located under router/index.js and update the route so that it can be used import() Function instead of import statement:

The following default configuration:

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

Change it to:

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

If you want, you can choose to load something on demand Instead of disabling prefetching and preloading globally for some pages, you can use special Webpack annotations and do not configure Webpack in vue.config.js:

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

import() The main difference between and import is that ES modules loaded by import() are loaded at runtime and ES modules loaded by import are loaded at compile time ES modules. This means that you can use import() to delay the loading of modules and load them only when necessary.

Implementing the progress bar

Because we cannot accurately estimate the loading time (or complete loading) of the page, we cannot real create a progress bar. There is also no way to check how much the page has loaded. But you can create a progress bar and have it complete when the page loads.

Since it cannot truly reflect progress, the progress depicted is just a random jump.

Install lodash.random first, because this package will be used to generate some random numbers during the process of generating the progress bar:

$ npm i lodash.random
Copy after login

Then, create a Vue componentcomponents/ProgressBar.vue:

<template>
    <p>
        </p>
<p>
            </p>
<p></p>
        
        <p></p>
    
</template>
Copy after login

Next add a script to the component. First import random and $eventHub in the script, which will be used later:

<script>
import random from &#39;lodash.random&#39;
import $eventHub from &#39;../components/eventHub&#39;
</script>
Copy after login

After importing, define some variables in the script that will be used later:

// 假设加载将在此时间内完成。
const defaultDuration = 8000 
// 更新频率
const defaultInterval = 1000 
// 取值范围 0 - 1. 每个时间间隔进度增长多少
const variation = 0.5 
// 0 - 100. 进度条应该从多少开始。
const startingPoint = 0 
// 限制进度条到达加载完成之前的距离
const endingPoint = 90
Copy after login

Then code the logic to implement asynchronous loading of components:

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)
        },
    },
}
Copy after login

In the mounted() function, use the event bus to listen to the loading of asynchronous components. Once the route tells us we've navigated to a page that hasn't loaded yet, it will start the loading animation.

Finally add some styling:

<style>
.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>
Copy after login

Finally add the ProgressBar to App.vue or the layout component as long as it is located with the route view Just in the same component, it is available throughout the life cycle of the application:

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

<script>
import ProgressBar from &#39;./components/ProgressBar.vue&#39;
export default {
       components: { ProgressBar },
}
</script>
Copy after login

Then you can see a smooth progress bar at the top of the page:

Implement Vue lazy loading with progress bar

Trigger progress bar for lazy loading

NowProgressBar is listening on the event bus for asynchronous component loading events. An animation should be triggered when certain resources are loaded this way. Now add a route guard to the route to receive the following events:

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()
})
Copy after login

为了检测页面是否被延迟加载了,需要检查组件是不是被定义为动态导入的,也就是应该为  component:() => import('...') 而不是component:MyComponent

这是通过 typeof to.matched[0]?.components.default === 'function' 完成的。带有  import 语句的组件不会被归为函数。

总结

在本文中,我们禁用了在 Vue 应用中的预取和预加载功能,并创建了一个进度条组件,该组件可显示以模拟加载页面时的实际进度。

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

作者:Stack Abuse

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Implement Vue lazy loading with progress bar. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template