Vue3 lazy-loading view from another view?

Is it possible to lazy-load a view from another? For example if the user is on /auth, while the user fills out some inputs it should lazy-load the Fillout component and when user is done push the route to Fillout from Auth.

This is a bit of a stretch since I haven't found anything on this in the docs. It would make sense to me that something like this should exist since using chunks loads all at once? Am I looking at this wrong?

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/fillout',
    name: 'Fillout',
    component: () => import('../views/Fillout.vue')
  },
  {
    path: '/auth',
    name: 'Auth',
    component: () => import('../views/Auth.vue')
  }
]
Thank you.


#1 Answers

As discussed in comments, just write a method in your component to prefetch the component you want to lazy load.

const prefetch = () => import('@/path/to/MyComponent');

And then call that method when you consider, i.e., when the user has filled some mandatory inputs or the form is valid, ...

This method call will cause an HTTP request to load the necessary chunks, so, when you navigate to the desired route, the component is actually fetched, and no additional HTTP requests are done.

Comments