How to implement lazy loading of Vue.js modules?

To implement lazy loading of Vue.js modules, you need to follow these steps:

  1. Define your routes using the Vue Router.

    import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', routes: [ { path: '/', name: 'home', component: () => import('./components/Home.vue'), }, { path: '/about', name: 'about', component: () => import('./components/About.vue'), }, // other routes ], }); export default router;
  2. Use the component function to dynamically import components when the route is visited. This is achieved by using JavaScript's dynamic import syntax.

    { path: '/about', name: 'about', component: () => import('./components/About.vue'), }
  3. Configure your build tool, such as Webpack or Vue CLI, to split your code into chunks for each route. This will ensure that each route's component is loaded only when needed.

  4. Optionally, you can use a loading component to display a loading state while the component is being loaded.

    <template> <div> <h1>Loading...</h1> </div> </template>
  5. Finally, make sure to add <router-view></router-view> to your main App component, which will render the matched component based on the current route.

    <template> <div id="app"> <router-view></router-view> </div> </template>

With lazy loading, the components will be loaded only when they are needed, reducing the initial bundle size and improving the load time of your application.