<div id="app"> <component :is="currentComponent"></component> <button @click="toggleComponent">切换组件</button> </div> <!-- Vue 3 CDN --> <script src="https://unpkg.com/vue@3.2.45/dist/vue.global.prod.js"></script> <script> const { createApp, defineComponent, ref, computed } = Vue; // 定义两个简单的组件 const ButtonPrimary = defineComponent({ template: `<button class="btn-primary">Primary Button</button>` }); const ButtonSecondary = defineComponent({ template: `<button class="btn-secondary">Secondary Button</button>` }); // 创建应用 const app = createApp({ setup() { // 控制当前要显示的组件 const isPrimary = ref(true); const currentComponent = computed(() => { return isPrimary.value ? ButtonPrimary : ButtonSecondary; }); // 切换组件的方法 const toggleComponent = () => { isPrimary.value = !isPrimary.value; }; return { currentComponent, toggleComponent }; } }); app.mount('#app'); </script>