提供选项式、组合式两种写法实现component的动态切换。
代码如下
javascript
<template>
<h3>测试</h3>
<button @click="currentTemplate =HelloWorld">切换到HelloWorld</button>
<button @click="currentTemplate =TheWelcome">切换到TheWelcome</button>
<button @click="switchComponent(curindex)">switchComponent切换</button>
<br/>
<component :is="p1 ? HelloWorld : TheWelcome" > </component>
<br/>
<component :is="currentTemplate" > </component>
</template>
<script setup>
import { ref} from 'vue'
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'
const p1 = true;
const currentTemplate = ref(HelloWorld); //赋值是重点 不能是 ref("HelloWorld")
const curindex = ref(1);
function switchComponent(index) {
console.log(index);
curindex.value = index+1;
if (index%2)
{
currentTemplate.value = TheWelcome;
}
else
{
currentTemplate.value = HelloWorld;
}
}
</script>
<!--
<script>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'
export default {
name: 'MainIndex',
components: {
HelloWorld,
TheWelcome,
},
data() {
return {
currentTemplate: "HelloWorld" //当前组件
};
},
methods: {
//切换 组件
toggleTemplate(activeTemplate) {
console.log("toggleTemplate() "+activeTemplate);
this.currentTemplate = activeTemplate;
},
}
}
</script> -->
<style scoped>
</style>