Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading