Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jackysee/b8ee4df5fac497b6e82d3fd30ed29208 to your computer and use it in GitHub Desktop.
Save jackysee/b8ee4df5fac497b6e82d3fd30ed29208 to your computer and use it in GitHub Desktop.
Use dynamic import with <suspense> in vue-router

In order to show a loading indicator when loading route.

  1. Use the vue document recommended syntax ( https://vuejs.org/guide/built-ins/suspense.html#combining-with-other-components )
  <router-view v-slot="{ Component }">
      <Suspense timeout="0">
          <component :is="Component" />
          <template #fallback>
             <spinner />
          </template>
      </Suspense>
  </router-view>
  1. The Component here needs to be a sync component. So in your route definition
    {
        path: '/user',
        name: 'user',
        component: () => Promise.resolve(() => h(defineAsyncComponent(() => import('./user.vue'))))
    },

Here () => Promise.resolve(....) is the dynamic import vue router use. () => h(...) is a functional vue component, which wraps around the async component defined by defineAsyncComponent(() => import(...)).

You can make it a factory function:

    const lazyRoute = (f) => () => Promise.resolve(() => h(defineAsyncComponent(f));

    {
        path: '/user',
        name: 'user',
        component: lazyRoute(() => import('./user.vue'))
    },
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment