Implement Vue lazy loading with progress bar
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.
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()
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') }, }
Add routes and pages
Use npx
Install Vue router and use:
$ npx vue add router
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 },
Change it to:
{ path: '/about', name: 'About', component: () => import('../views/About.vue') },
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' )
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
Then, create a Vue componentcomponents/ProgressBar.vue
:
<template> <p> </p> <p> </p> <p></p> <p></p> </template>
Next add a script to the component. First import random
and $eventHub
in the script, which will be used later:
<script> import random from 'lodash.random' import $eventHub from '../components/eventHub' </script>
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
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) }, }, }
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>
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 './components/ProgressBar.vue' export default { components: { ProgressBar }, } </script>
Then you can see a smooth progress bar at the top of the page:
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() })
为了检测页面是否被延迟加载了,需要检查组件是不是被定义为动态导入的,也就是应该为 component:() => import('...')
而不是component:MyComponent
。
这是通过 typeof to.matched[0]?.components.default === 'function'
完成的。带有 import
语句的组件不会被归为函数。
总结
在本文中,我们禁用了在 Vue 应用中的预取和预加载功能,并创建了一个进度条组件,该组件可显示以模拟加载页面时的实际进度。
原文:https://stackabuse.com/lazy-loading-routes-with-vue-router/
作者:Stack Abuse
相关推荐:
更多编程相关知识,请访问:编程入门!!
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
