Vue3 component is not rendering when imported using options API

186 Views Asked by At

So I created a fresh vue3 application and a vue3 module. The application is using the vue3 module as a dependency. In the vue3 module, I am just exporting a component (this component has a child components). In the application, the exported component from the module renders but the child components doesn't render. (getting a vue warning "resolveComponent can only be used in render() or setup()."). Currently using options API in the module, but when I switched to composition api (using <script setup>), the child components of the module renders with no problem.

I kinda want to stick with options API because currently I am migrating a enterprise module from vue2 to vue3, and I want to avoid big changes if possible. (All of the components in the module are using options API, and re-writing it to composition API will take a lot of time).

exported component in the module, AppVue3.vue:

<template>
  <div>
    <h1>Test App Vue 3</h1>
    <ModuleHelloWorld msg="Vite + Vue"></ModuleHelloWorld>
  </div>
</template>

<script>
import ModuleHelloWorld from './components/ModuleHelloWorld.vue'

export default {
  components: {
    ModuleHelloWorld
  },
  created() {
    console.log('App Vue 3 CREATED');
  }
};
</script>

ModuleHelloWorld.vue:

<template>
  <div>
    <h1>{{ msg + ' hehe' }}</h1>
    <h1>Test Hello World</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  components: {
    SecondComponent
  },
  props: ['msg'],
  created() {
    console.log('THIS IS CREATED');
  },
}
</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>

ModuleHelloWorld.vue is not rendering when options API is used in AppVue3.vue. But when I use <script setup>, ModuleHelloWorld.vue is rendering with no problem:

<template>
  <div>
    <h1>Test App Vue 3</h1>
    <ModuleHelloWorld msg="Vite + Vue"></ModuleHelloWorld>
  </div>
</template>

<script setup>
import ModuleHelloWorld from './components/ModuleHelloWorld.vue'
</script>

I'm searching for hours now and can't find any relevant solutions. I will really appreciate any help, thank you!

1

There are 1 best solutions below

0
On

Try to use defineAsyncComponent. Import from vue defineAsyncComponent

import { defineAsyncComponent } from 'vue'

and then: remove this:

import ModuleHelloWorld from './components/ModuleHelloWorld.vue'
components: { ModuleHelloWorld },

and add this

  components: {
        "ModuleHelloWorld": defineAsyncComponent(() => import('./components/ModuleHelloWorld.vue')) 
}