vue3 动态组件使用报错:
Vue 提示如果动态组件绑定的是一个ref 的响应式对象会造成不必要的性能问题,建议用 markRaw 或者 shallowRef 代替 ref
由于Vue3中动态组件绑定的是组件实力并不是组件名称,所以用shallowRef
来解决:
如下所示:
<script setup>
import { ref, shallowRef} from "vue";
import CompA from "./CompA.vue";
import CompB from "./CompB.vue";
import CompC from "./CompC.vue";
import CompD from "./CompD.vue";
const name = ref("CompA");
const currentComp = shallowRef(CompA);
const compsObj = shallowRef({
CompA,
CompB,
CompC,
CompD,
});
function changeComp(v) {
currentComp.value = compsObj.value[v];
}
</script>
<template>
<Space direction="vertical" size="large">
<RadioGroup v-model="name" @on-change="changeComp">
<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>