javascriptvuejs3quasar-frameworkquasarvue-dynamic-components

using dynamic components in vue with composition API


Im trying to create a dynamic component in Vue 3 (quasar) using composition API. But I cannot render the components using composition API. While this works fine:

<template>
  <p>
    <button @click="component = 'ComponentA'">Comp A</button>
    <button @click="component = 'ComponentB'">Comp B</button>
  </p>

  <component :is="component" />
</template>

<script>
import ComponentA from "../components/ComponentA.vue";
import ComponentB from "../components/ComponentB.vue";

export default {
  components: {
    ComponentA,
    ComponentB,
  },
  data() {
    return {
      component: "ComponentA",
    };
  },
};
</script>

The dynamic component wont work using setup

<template>
  <q-page class="flex column flex-center background-white">
    <q-btn @click="component = 'ComponentA'"
      >ComponentA</q-btn
    >
    <q-btn @click="component = 'ComponentB'"
      >ComponentB</q-btn
    >
    <component :is="component" />
  </q-page>
</template>
<script setup>
import { ref, defineAsyncComponent } from "vue";

const component = ref("ComponentA");

const ComponentA = defineAsyncComponent(() =>
  import("../components/ComponentA.vue")
);
const ComponentB = defineAsyncComponent(() =>
  import("../components/ComponentB.vue")
);
</script>

what do I miss?


Solution

  • You're assigning your component as a string 'componentA', not a component.

    const components = ref();
    onMounted(() => {
        const ComponentA= defineAsyncComponent(() =>
        import("./ComponentA.vue")
        );
        components.value = ComponentA;
    })