vue.jsvue-routervuejs3vue-router4

How to use createAsyncComponent in VueRouter@4.0.0 (Vue3)?


When I fill the component field in createRouter() like this:

{
    path: '/article/post',
    name: 'article-post',
    component: defineAsyncComponent({
      loader: () => import('@/views/article-post/index.vue'),
      loadingComponent: () => import('@/views/article-post/skeleton.vue'),
    }),
},

Seems like it's not working. What I want it to show a loading page when the actual page is loading.

How do I do that?


Solution

  • The loadingComponent value must be a component definition, and cannot itself be an async component:

    import { createRouter } from 'vue-router'
    import { defineAsyncComponent } from 'vue'
    import Skeleton from '@/views/article-post/skeleton.vue'
    
    export default createRouter({
      routes: [
        {
          path: '/article/post',
          name: 'article-post',
          component: defineAsyncComponent({
            loader: () => import('@/views/article-post/index.vue'),
            //loadingComponent: () => import('@/views/article-post/skeleton.vue'), ❌ cannot be dynamic import
            loadingComponent: Skeleton ✅
          }),
        },
      ]
    })
    

    Also note that the loading component (Skeleton) is only shown once, i.e., if the component definition is not already in cache. This Codesandbox adds an artifical delay in loader() to demonstrate.