Home >Web Front-end >Vue.js >Introduction to the method of implementing lazy loading of routes with vue+webpack2

Introduction to the method of implementing lazy loading of routes with vue+webpack2

青灯夜游
青灯夜游forward
2020-11-05 17:47:111993browse

The following Vue.js Tutorial column will introduce to you how vue webpack2 implements lazy loading of routing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Introduction to the method of implementing lazy loading of routes with vue+webpack2

When packaging and building an application, the Javascript package can become very large, affecting page loading. It would be more efficient if we could split the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed.

Combine Vue’s asynchronous components and Webpack’s code splitting function to easily implement lazy loading of routing components.

First, the asynchronous component can be defined as a factory function that returns a Promise (the Promise returned by this function should resolve the component itself):

const Foo = () => Promise.resolve({ /* 组件定义对象 */ })

Second, in Webpack 2, we can use Dynamic import syntax to define code split points:

import('./Foo.vue') // 返回 Promise

Combining the two, this is how to define an asynchronous component that can be automatically code split by Webpack.

const Foo = () => import('./Foo.vue')

Nothing needs to be changed in the routing configuration, just use it as usual Foo:

const router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo }
  ]
})

Related recommendations:

2020 Summary of front-end vue interview questions (with answers)

vue tutorial recommendation: 2020 latest 5 vue.js video tutorial selections

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Introduction to the method of implementing lazy loading of routes with vue+webpack2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete