Async Components in Vue 3

Always in my long journey to learn Vue 3, It may happen that I use code snippets that are told to be compatible with Vue 3 when they are not in reality. Many examples use old code snippets, so if you have an unexpected error, think about visiting the transition guide.

The component does not load, and a warning shows in the console. This warning may contain the following message:

[Vue warn]: Invalid VNode type: undefined (undefined)

Async Component

Vue 2

To create an async component (a lazy-loaded component) in Vue 2, we define a component as a function that returns a promise, such as:

export default {
    name: "Component"
    components: {
        AnotherComponent: () => import (uri),
    }
}

That does not work anymore in Vue 3 because functional components are now defined as pure functions.

Vue 3

In Vue 3, we have to wrap the definition into a new function that needs to be imported.

The function is called: defineAsyncComponent

import { defineAsyncComponent } from 'vue';

export default {
	name: "Component"
	components: {
		AnotherComponent: defineAsyncComponent(() => import (uri)),
	}
}

3 comments:

  1. This change wasted three hours of my life. I wish I had seen your post much earlier!

    ReplyDelete
    Replies
    1. I have wasted a lot more back then, and I didn't have a vue 2 background.
      Happy to help

      Delete
    2. Great, thank you!

      For who not uses ES6:

      app.component("loading", Vue.defineAsyncComponent(window.httpVueLoader("path/to/my_component.vue")));

      Delete

Powered by Blogger.