Concept (lazy loading)
When building an application in package, the JavaScript package becomes very large, affecting page loading. If we can divide the corresponding components of different routes into different code blocks, and then load the corresponding components when the route is accessed, well, this will be more efficient.
Scene
As a single-page application, the xxx project adopts a componentized development model. All components will be loaded every time the home page is started. However, at this time, it is just visiting the home page, which causes a large number of components to be polluted and loaded.
Purpose
Only load the corresponding components when accessing the current page to avoid all page components loading. (Load on demand)
accomplish
<template> <div > <router-view/> </div> </template>
import Vue from 'vue' import VueRouter from 'vue-router' import 'babel-polyfill' import {Promise} from 'es6-promise-polyfill' import App from '../components/app' // Define routes, each route maps one component.const Routers = [ { path: '/', // Path component: resolve => require(['../components/member/index], resolve) // Asynchronously load components }, { path: '/login', component: resolve => require(['../components/member/login'], resolve) } ] const RouterConfig = { routes: Routers } // Create a router instance and pass the routing configuration.const router = new VueRouter(RouterConfig); // Create and mount the root instance.new Vue({ el:'#app', router, // It is a common convention to use h as an alias for createElement. render: h =>(App) })
Notice:
The require() function accepts two parameters. The first parameter is an array representing the dependent module, such as ['moduleA','moduleB'], and the second parameter is a callback function. After all the currently specified modules are loaded successfully, it will be called. The loaded module is passed in the function as a parameter, so that these modules are used inside the callback function.
The sample code uses an asynchronous method to load components, where the require function is responsible for asynchronously introducing the components to be rendered, while resolve is responsible for asynchronous callback rendering components.
babel-polyfill: transcoding and compiling Promise;
npm install --save babel-polyfill
es6-promise-polyfill solves Promise compatibility issues. For students who don’t know much about Promise, please go here
npm install --save es6-promise-polyfill
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.