1.不使用setup語(yǔ)法糖,這種方式和vue2差不多,is可以是個(gè)字符串
<template>
<Child1 />
<Child2 />
<component :is="currentComp"></component>
<el-button @click="compChange">切換組件</el-button>
</template>
<script>
import { ref } from 'vue'
import Child1 from './Child1.vue'
import Child2 from './Child2.vue'
export default {
components: {
Child1,
Child2
},
setup() {
let currentComp = ref('Child1')
// 切換組件
const compChange = () => {
if(currentComp.value == 'Child1') {
currentComp.value = 'Child2'
}else {
currentComp.value = 'Child1'
}
}
return {
currentComp,
compChange
}
}
}
</script>
2. 使用setup語(yǔ)法糖,這時(shí)候的is如果使用字符串會(huì)加載不出來(lái),得使用組件實(shí)例
第一種方式文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-573438.html
<template>
<Child1 />
<Child2 />
<component :is="flag ? Child1 : Child2"></component>
<el-button @click="flag = !flag">切換組件</el-button>
</template>
<script setup>
import { ref } from 'vue'
import Child1 from './Child1.vue'
import Child2 from './Child2.vue'
const flag = ref(true)
</script>
第二種方式文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-573438.html
<template>
<Child1 />
<Child2 />
<component :is="currentComp"></component>
<el-button @click="compChange">切換組件</el-button>
</template>
<script setup>
import { shallowRef, ref } from 'vue'
import Child1 from './Child1.vue'
import Child2 from './Child2.vue'
//這里用ref的話,vue給出警告Vue接收到一個(gè)組件,該組件被制成反應(yīng)對(duì)象。這可能會(huì)導(dǎo)致不必要的性能開(kāi)銷,應(yīng)該通過(guò)將組件標(biāo)記為“markRaw”或使用“shallowRef”而不是“ref”來(lái)避免。
// 如果使用 markRaw 那么currentComp將不永遠(yuǎn)不會(huì)再成為響應(yīng)式對(duì)象。 所以得使用 shallowRef
let currentComp = shallowRef(Child1)
// 切換組件
const compChange = () => {
if(currentComp.value == Child1) {
currentComp.value = Child2
}else {
currentComp.value = Child1
}
}
</script>
到了這里,關(guān)于Vue3中使用component :is 加載組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!