How to use Vue Router's lazy loading with vue-class-component?

490 views Asked by At

I'm still fairly new to Vue, and trying to implement lazy loaded routes on a project that uses class style components. Currently the components are defined for the routes using Webpack's dynamic import like so:

{
  path: '/dashboard',
  name: 'dashboard',
  component: function() {
    return import(
      /* webpackChunkName: "dashboard" */ '../components/content-views/content-main/ContentDashboard.vue'
    );
  },
},

But this doesn't seem to be working, as loading the app with an empty cache downloads all of the chunks up front, resulting in an enormous app file. Reading the documentation, it looks like I need to define the class components as async by returning a Promise which resolves with the component. However, I'm honestly not sure if that's possible with a component which is a class definition, as opposed to a typical object-based one. The vue-class-component documentation doesn't mention this, but I'm wondering if there's some kind of alternative syntax for achieving this, or if I'm missing something else.

Any assistance appreciated!

2

There are 2 answers

0
aayushrestha On

just as MaBbKhawaja said,

path: "/",
    name: "index",
    component: () =>
        import("../views/Index.vue")

you can also assign chunkName like this

path: "/",
    name: "index",
    component: () =>
        import(/* webpackChunkName: "Home" */ "../views/Index.vue")

The docs gives a better explanation

0
MaBbKhawaja On

This is how you can use lazy routing in vuejs

path: "/",
    name: "index",
    component: () =>
        import("../views/Index.vue")