javascript 在vue中使用动态组件与组合API [重复]

sgtfey8w  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(143)

此问题已在此处有答案

Why doesn't the component tag in Vue3 work properly for dynamically rendering components?(4个答案)
昨天关门了。
我试图使用组合API在Vue 3(类星体)中创建一个动态组件。但是我不能使用composition API呈现组件。虽然这工作正常:

<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>

动态组件无法使用安装程序工作

<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>

我错过了什么

5fjcxozz

5fjcxozz1#

您将组件指定为字符串'componentA',而不是组件。

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

相关问题