Blog>
Snippets

Implementing Lazy Loading with Vue Router

Demonstrate how to use dynamic import() to achieve lazy loading and code splitting in Vue Router, to only load the component when required.
import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

const routes = [
  {
    path: '/home',
    name: 'Home',
    // The component will only be loaded when this route is visited.
    component: () => import('./components/Home.vue')
  },
  {
    path: '/about',
    name: 'About',
    // This route's component will be loaded dynamically as well.
    component: () => import('./components/About.vue')
  }
];

// Create the router instance and pass the `routes` option
const router = new Router({
  routes,
  // Use history mode to avoid hashes in URL.
  mode: 'history'
});

export default router;
This code sets up Vue Router with lazy loaded components. The import() function within the route definitions ensures that 'Home.vue' and 'About.vue' components are loaded only when the user navigates to their respective routes, saving bandwidth and improving initial page load time.