SoFunction
Updated on 2025-04-05

Summary of 3 ways of lazy loading of vue-router

Lazy loading is not used

import Vue from 'vue';
import Router from 'vue-router';
import HelloWorld from '@components/HelloWorld';
(Router);
export default new Router({
routes:[
	{path:'./',
	name:'HelloWorld',
	component:HelloWorld
	}
]
})

vue asynchronous component

component:resolve=>{reuqire(['Route Address Need to Load']),resolve)

import Vue from 'vue';
import Router from 'vue-router';
const HelloWorld=resolve=>{require(["@/components/HelloWorld"],resolve}
(Router);
export default new Router({
routes:[
	{path:'./',
	name:'HelloWorld',
	component:HelloWorld
	}
]
})

ES6's import()

import Vue from 'vue';
import Router from 'vue-router';
import HelloWorld=()=>import('@/components/HelloWorld');
('Router')
export default new Router({
	routes:[{
	{path:'./',
	name:'HelloWorld',
	component:HelloWorld
	}
	}]
})

webpack()

It can realize on-demand loading resources, including js, css, etc. He will package the required files separately and will not be packaged with the main file.

The first parameter is an array, indicating that the modules that need to be depended on in the second parameter will be loaded in advance.

The second is the callback function. In this callback function, the required file will be packaged separately into a chunk and will not be packaged with the main file. This way, two chunks are generated, and only the main file is loaded when loading the first time.

The third parameter is the error callback.

The fourth parameter is the file name of the chunk that is packaged separately

import Vue from 'vue';
import Router from 'vue-router';
const HelloWorld=resolve=>{
		(['@/components/HelloWorld'],()=>{
			resolve(require('@/components/HelloWorld'))
		})
	}
('Router')
export default new Router({
	routes:[{
	{path:'./',
	name:'HelloWorld',
	component:HelloWorld
	}
	}]
})

Summarize

This is the end of this article about 3 ways to lazy load vue-router. For more related content about lazy loading of vue-router, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!