Vue Router Implementation: Lazy Loading and History Modes
Implementing Lazy Loading in Vue Router
Standard component loading without lazy loading:
import ArticleList from '@/components/ArticleList.vue';
const routerConfig = new VueRouter({
routes: [
{ path: '/articles', component: ArticleList }
]
});
Method 1: Arrow Function with Dynamic Import (Most Common)
const ArticleList = () => import('@/components/ArticleList.vue');
const routerConfig = new VueRouter({
routes: [
{ path: '/articles', component: ArticleList }
]
});
Method 2: Arrow Function with require
const routerConfig = new VueRouter({
routes: [
{
path: '/articles',
component: resolve => require(['@/components/ArticleList'], resolve)
}
]
});
Method 3: Webpack's require.ensure
This method allows bundling multiple routes into a single file by specifying the same chunkName.
// `r` represents the resolve function
const ArticleList = r => require.ensure([], () => r(require('@/components/ArticleList')), 'article-module');
const routerConfig = new VueRouter({
routes: [
{
path: '/articles',
component: ArticleList,
name: 'articles'
}
]
});
Comparison Between Hash and History Modes in Vue Router
Vue Router operates in two primary modes: hash mode (default) and history mode.
Hash Mode
- URL Pattern: Includes a
#symbol, e.g.,www.example.com/#/profile. - Characteristics: The hash segment (
#/profile) is not sent to the server during HTTP requests, making it purely a client-side feature. Changing the hash does not trigger a page reload. Its widely supported across browsers, including older versions of Internet Explorer, and is standard for Single Page Applications (SPAs). - Underlying Mechanism: Relies on the
hashchangebrowser event.
window.addEventListener('hashchange', function(event) {
console.log('Previous URL:', event.oldURL, 'New URL:', event.newURL);
const currentHash = window.location.hash.substring(1); // Removes the '#'
});
The browser maintains a history stack for hash changes, enabling forward and backward navigation without server requests.
History Mode
- URL Pattern: Produces clean URLs without the hash, e.g.,
www.example.com/profile/123. - Characteristics: Requires proper server-side configuration to handle direct URL access or page refreshes; otherwise, a 404 error may occur. It provides a more traditional and aesthetically pleasing URL structure.
- API: The History API includes methods for state management and navigation.
- Modify History:
pushState()andreplaceState()change the URL and history state without causing a page reload. - Navigate History:
back(),forward(), andgo()control browser navigation.
- Modify History:
Enabling History Mode
const routerConfig = new VueRouter({
mode: 'history',
routes: [...] // Your route definitions
});
Key Differences
Using history.pushState() offers advantages over modifying the hash:
- It allows setting a new URL to any location with the same origin, whereas hash changes are restricted to the current document's fragment identifier.