什么是動態(tài)組件 就是:讓多個組件使用同一個掛載點(diǎn),并動態(tài)切換,這就是動態(tài)組件。
在掛載點(diǎn)使用component標(biāo)簽,然后使用v-bind:is=”組件?,通過is 切換 A B 組件
<template>
<div style="display: flex;">
<div @click="switchCom(item,index)"
:class="[active == index ? 'active':'']"
class="tabs" v-for="(item,index) in data" :key="index">
<div>{{ item.name }}</div>
</div>
</div>
<!-- 內(nèi)置組件 -->
<component :is="comId"></component>
</template>
<script setup lang='ts'>
import { ref, reactive, shallowRef, markRaw } from 'vue'
import AP from '@/components/expame/AP.vue'
import BP from '@/components/expame/BP.vue'
import CP from '@/components/expame/CP.vue'
const comId = shallowRef(AP) // 切換組件
const active = ref(0) // 點(diǎn)擊tab動態(tài)樣式
const data = reactive([
{
name:'A組件',
com:markRaw(AP)
},
{
name:'B組件',
com:markRaw(BP)
},
{
name:'C組件',
com:markRaw(CP)
}
])
// 點(diǎn)擊事件
const switchCom = (item , index) => {
comId.value = item.com
active.value = index
}
</script>
使用場景
tab切換?居多
注意事項(xiàng)?
1.在Vue2 的時候is 是通過組件名稱切換的 在Vue3 setup 是通過組件實(shí)例切換的
2.如果你把組件實(shí)例放到Reactive Vue會給你一個警告runtime-core.esm-bundler.js:38 [Vue warn]: Vue received a Component which was made a reactive object. This can lead to unnecessary performance overhead, and should be avoided by marking the component with `markRaw` or using `shallowRef` instead of `ref`.?
Component that was made reactive:?文章來源:http://www.zghlxwxcb.cn/news/detail-644675.html
這是因?yàn)閞eactive 會進(jìn)行proxy 代理 而我們組件代理之后毫無用處 節(jié)省性能開銷 推薦我們使用shallowRef 或者 ?shallowRef 跳過proxy 代理
所以上面要使用shallowRef , shallowRef 包裹組件文章來源地址http://www.zghlxwxcb.cn/news/detail-644675.html
到了這里,關(guān)于(vue3)動態(tài)組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!