在Vue3开发中会发现直接使用动态组件,不像Vue2中那样丝滑了,不是动态绑定组件名就能跑起来的,发现下面的尴尬:
看问题现象:

聪明的你来看看你是不是也是这么写的:
结果你已经看到了,就是上面那张很精彩的效果
so, 我们直接 请出官文:Vue3 components 动态组件在setup 中的应用
其中动态组件中第一句话便是:
由于组件是通过变量引用而不是基于字符串组件名注册的,在
name和currentName的ref()就应该是个组件类型,非组件名称字符串痛改前非后,其实有两种方式可解决
所以还是仔细看API,多翻阅,多尝试
部分不动: 我还是我,我只是坐地日行八万里,我很专一,没有变,我允许你无视我
// main.js
import CompA from "./components/CompA.vue";
import CompB from "./components/CompB.vue";
import CompC from "./components/CompC.vue";
import CompD from "./components/CompD.vue";
const app = createApp(App);
app
.component("CompA", CompA)
.component("CompB", CompB)
.component("CompC", CompC)
.component("CompD", CompD);
// 刚才的代码 compotent.vue
<script setup>
import { ref, watch } from "vue";
const name = ref('CompA'); // 就写字符串
const currentComp = ref('CompA');// 就写字符串
watch(name, (v) => {
currentComp.value = v // 我还写字符串
})
</script>
<template>
<Space direction="vertical" size="large">
<RadioGroup v-model="name">
<Radio label="CompA"></Radio>
<Radio label="CompB"></Radio>
<Radio label="CompC"></Radio>
<Radio label="CompD"></Radio>
</RadioGroup>
</Space>
<KeepAlive :include="['CompA', 'CompC']">
<component :is="currentComp"></component>
</KeepAlive>
</template>
