Vue3动态组件使用例子,解决Vue received a Component which was made a reactive object.
<template>
<div>
<component :is="currentComponent"></component>
<button @click="switchComponent">Switch Component</button>
</div>
</template>
<script>
import { ref, defineComponent } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default defineComponent({
components: {
ComponentA,
ComponentB
},
setup() {
const currentComponent = ref(ComponentA);
function switchComponent() {
currentComponent.value = currentComponent.value === ComponentA ? ComponentB : ComponentA;
}
return {
currentComponent,
switchComponent
};
}
});
</script>
这个例子展示了如何在Vue 3中使用动态组件以及如何在不同组件之间切换。currentComponent
是一个响应式引用,它被初始化为 ComponentA
。通过点击按钮,可以调用 switchComponent
函数来改变 currentComponent
的值,从而实现组件的切换。这个例子简单明了,并且正确地处理了响应式变更。
评论已关闭