Lazy loading in Vue.js refers to the practice of loading components only when they are actually needed, which can improve the initial loading time of your application. This is typically achieved using Vue's built-in import
function or dynamic import()
syntax, which allows you to load a component asynchronously. Here's a step-by-step guide on how to implement lazy loading in Vue.js:
Create a Vue Project: If you don't have a Vue project yet, you can create one using Vue CLI. Install Vue CLI globally and then create a new project:
bashnpm install -g @vue/cli
vue create your-project-name
cd your-project-name
Create Components:
Create the components you want to lazy load. For example, you might have a Home
component and a About
component.
html<!-- components/Home.vue -->
<template>
<div>
<h1>Home Component</h1>
</div>
</template>
html<!-- components/About.vue -->
<template>
<div>
<h1>About Component</h1>
</div>
</template>
Lazy Load Components: In your main component or route configuration, use dynamic import to lazily load the components:
html<!-- App.vue -->
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
};
</script>
javascript// router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const Home = () => import(/* webpackChunkName: "home" */ '../components/Home.vue');
const About = () => import(/* webpackChunkName: "about" */ '../components/About.vue');
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
];
const router = new VueRouter({
routes,
});
export default router;
In this example, the import()
statements are used to load the components asynchronously. The webpackChunkName
comment is optional and is used to name the chunks generated by Webpack.
Configure Webpack: Ensure that your Webpack configuration supports dynamic imports. This is usually the case with Vue CLI projects out of the box.
Run Your Project:
Run your Vue.js project and observe the lazy loading behavior. When you navigate to the /about
route, for example, the About
component will be loaded only when needed.