Analysis of vue2 component implementation in lazy loading; analysis of vue2 component

Source: Internet
Author: User

Analysis of vue2 component implementation in lazy loading; analysis of vue2 component

1. What is lazy loading?

Lazy loading is also called delayed loading, that is, loading as needed and on-demand loading.

Ii. Why do I need to load it lazily?

In a single-page application, if no application is lazy to load, the files packaged using webpack will be abnormally large, resulting in too much content to be loaded when you enter the home page, resulting in a long delay, it is not conducive to the user experience, while lazy loading can be used to divide pages. Loading pages when needed can effectively share the loading pressure on the home page and reduce the loading time on the home page.

3. How to work with webpack to implement component lazy loading

1. Configure the chunkFilename attribute in the output path of the webpack configuration file.

output: {    path: resolve(__dirname, 'dist'),    filename: options.dev ? '[name].js' : '[name].js?[chunkhash]',    chunkFilename: 'chunk[id].js?[chunkhash]',    publicPath: options.dev ? '/assets/' : publicPath  }, 

The chunkFilename path will be used as the path for component lazy loading.

2. asynchronous loading methods supported by webpack

  • Resolve => require ([URL], resolve), good support
  • () => System. import (URL), which has been declared on the webpack2 official website will be gradually abolished and is not recommended.
  • () => Import (URL), which is recommended on the official website of webpack2 and belongs to the es7 category. It must be used with the syntax-dynamic-import plug-in of babel. The usage is as follows:

Copy codeThe Code is as follows:
Npm install -- save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015

use: [{    loader: 'babel-loader',    options: {     presets: [['es2015', {modules: false}]],     plugins: ['syntax-dynamic-import']    }   }] 

4. Implement lazy loading in specific instances

1. Configure asynchronous components in routes

Export default new Router ({routes: [{mode: 'History ', path:'/my', name: 'My ', component: resolve => require (['.. /page/my. vue '], resolve), // lazy loading},]})

2. Configure asynchronous components in the instance

Components: {historyTab: resolve => {require (['.. /.. /component/historyTab. vue '], resolve)}, // lazy loading // historyTab: () => import ('.. /.. /component/historyTab. vue ')},

3. Register asynchronous components globally

Vue.component('mideaHeader', () => {  System.import('./component/header/header.vue')}) 

5. configuring asynchronous components to implement lazy loading

1. Will multiple accesses to the same asynchronous page load cause multiple component loading?

A: No. When a component is used for the first time, the browser sends a request to load the component. After the component is loaded, it will be cached for calling when the component is used again.

2. Is it possible to load components multiple times when the same asynchronous component is used in multiple places? For example:

// Export default {components: {historyTab: resolve => {require (['.. /.. /component/historyTab. vue '], resolve)}, // lazy loading},} // B page export default {components: {historyTab: resolve => {require (['.. /.. /component/historyTab. vue '], resolve)}, // lazy loading },}

A: No. The reason is the same as above.

3. Will resource reuse occur if the same component is synchronized and asynchronously loaded on two asynchronously loaded pages? For example:

// Import historyTab from 'on page '.. /.. /component/historyTab. vue '; export default {components: {historyTab},} // export default {components: {historyTab: resolve => {require (['.. /.. /component/historyTab. vue '], resolve)}, // lazy loading },}

A: Yes, it will cause resource reuse. According to the output after packaging, the historyTab component code is embedded in page a. The historyTab component on page B is asynchronously loaded, in addition, package chunk;

Solution: During component development, if the root page does not import components, but the components are used in other asynchronous loading pages, the maximum utilization of resources is realized, during collaborative development, all users use Asynchronous component loading.

4. Does rendering delay impact on the page when embedded components asynchronously loaded on the page are loaded asynchronously?

A: Yes, the asynchronously loaded components will lag behind other elements in the page, and the page will be instantly flashed;

Solution: Because the loading time may occur when the component is loaded for the first time and the page lags behind, a proper page structure design is required to avoid the first hop flash;

6. The final implementation scheme of lazy loading

1. components on the routing page and routing page are all loaded lazily.

Advantages: (1) Maximize On-Demand

(2) team development will not cause repeated waste of resources due to communication issues

Disadvantages: (1) Multiple http requests are sent when multiple components are nested in a page, which may cause slow page display and uneven rendering.

2. the routing page uses lazy loading, while the components on the routing page are loaded on demand. That is, if the components are not large and are not frequently used, you can directly import the components on the routing page, if components are used more frequently, use lazy loading.

Advantages: (1) it can reduce http requests on the page and display the page better.

Disadvantages: (2) the team needs to communicate with each other in advance and create a folder for the components to be loaded in the framework.

3. the routing page uses lazy loading. When the display delay of the home page is not particularly affected, the root page can be properly imported and reused components, combined with solution 2.

Advantages: (1) properly solves the problem of homepage delay display

(2) It can minimize http requests and achieve the best display effect on other routing interfaces.

Disadvantages: (1) it is still necessary for a team to communicate with each other and establish component folders that distinguish various loading methods.

7. Use the third solution to design the directory structure

  

8. Specific Code implementation design

1. Routing Design:

Import Router from 'vue-router '; import vue from 'vue'; Vue. use (Router); export default new Router ({routes: [{mode: 'History ', path:'/home', name: 'home', component: resolve => require ([URL], resolve), // lazy loading children: [{mode: 'History ', path:'/home/: name', name: 'any', component: resolve => require (['.. /page/any. vue '], resolve), // lazy loading},]}, {mode: 'History', path: '/store', name: 'store', component: resolve => require (['.. /page/store. vue '], resolve), // lazy loading, children: [{mode: 'History', path: '/store/: name', name: 'any', component: resolve => require (['.. /page/any. vue '], resolve), // lazy loading},]}, {mode: 'History', path: '/my', name: 'My', component: resolve => require (['.. /page/my. vue '], resolve), // lazy loading, children: [{mode: 'History', path: '/my/: name', name: 'any', component: resolve => require (['.. /page/any. vue '], resolve), // lazy loading},]},]})

(1) The tab page corresponding to the routing root component at the first layer

(2) the root directory is followed by the Child routing page. The child routing adopts dynamic routing and route-based programming navigation plus vuex to optimize and improve development efficiency.

Directly paste the Code:

/*** Created by ZHANZF on 2017-3-20. * // vuex configure import Vue from 'vue '; import Vuex from 'vuex'; vue. use (Vuex); export default new Vuex. store ({state: {// route Component Memory routers :{}}, getters: {routers: state =>{ return state. data ;}, mutations: {// dynamically add route addRouter: (state, data) =>{ state. routers = Object. assign ({}, state. routers, {[data. name]: data. component}) ;}}, actions: {acMethods ({commit}) {}},}) // register the routing component window in the root directory. midea = {registerRouter (name, component) {Store. commit ('addrouter ', {name: name, component: component}) }}; // use the routing navigation openAnyPage () {midea. registerRouter ('module', resolve => {require (['.. /module. vue '], resolve)}); // load this. $ router. push ({path: '/home/module', query: {title: this. title }});}
// Use the dynamic component <template> <component: is = "currentRouter": moduleName = "title"> </component> </template> <script src = ". /any. js "> export default {data () {return {routeName:'', currentRouter: '', title:'', }}, created () {this. routeName = this. $ route. params. name; this. title = this. $ route. query. title; this. currentRouter = this. $ store. state. routers [this. routeName] ;}, methods :{}</script>

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.