Vue3動態(tài)組件<component>渲染失效原因分析
在Vue2中偽代碼如下:
<template>
<component
:is="currentActiveTab.component"
ref="componentRef"
:key="currentActiveTab.key"
:current-active-tab="currentActiveTab"
v-bind="currentActiveTab"
/>
</template>
<script>
import A from './components/A'
import B from './components/B'
import C from './components/C'
export default {
components: {
A,
B,
C
},
data() {
return {
tabList: [
{
name: '概覽視圖',
key: 'all',
component: 'OverviewGraph'
}
],
activetab: 'all',
}
},
computed: {
currentActiveTab() {
return this.tabList.find((v) => v.key === this.activetab)
}
}
}
</script>
遷移到Vue3中代碼如下:
<template>
<component
:is="currentActiveTab.component"
ref="componentRef"
:key="currentActiveTab.key"
:current-active-tab="currentActiveTab"
v-bind="currentActiveTab"
/>
</template>
<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import A from './components/A.vue'
import B from './components/B.vue'
import C from './components/C.vue'
const tabList = ref([
{
name: '概覽視圖',
key: 'all',
component: 'OverviewGraph'
}
])
const activetab = ref('all')
const currentActiveTab = computed(() => {
return tabList.value.find((v) => v.key === activetab.value)
})
</script>
Vue3渲染出來是醬紫的:

只有一個殼子,沒有任何內(nèi)容。
問題出在組件的名字上了:在 <script setup> 中要使用動態(tài)組件時,需要直接用 :is="Component" 直接綁定到組件本身,而不是字符串的組件名。 也就是需要把'OverviewGraph'改成OverviewGraph即可。 修改后的代碼如下:
<template>
<component
:is="currentActiveTab.component"
ref="componentRef"
:key="currentActiveTab.key"
:current-active-tab="currentActiveTab"
v-bind="currentActiveTab"
/>
</template>
<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import A from './components/A.vue'
import B from './components/B.vue'
import C from './components/C.vue'
const tabList = ref([
{
name: '概覽視圖',
key: 'all',
component: OverviewGraph // 改了這里
}
])
const activetab = ref('all')
const currentActiveTab = computed(() => {
return tabList.value.find((v) => v.key === activetab.value)
})
</script>
到此這篇關(guān)于Vue3動態(tài)組件<component>渲染失效原因分析的文章就介紹到這了,更多相關(guān)Vue3 component渲染失效內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue鼠標hover(懸停)改變background-color移入變色問題
這篇文章主要介紹了vue鼠標hover(懸停)改變background-color移入變色問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
vue中v-model指令與.sync修飾符的區(qū)別詳解
本文主要介紹了vue中v-model指令與.sync修飾符的區(qū)別詳解,詳細的介紹了兩個的用法和區(qū)別,感興趣的可以了解一下2021-08-08
vue實現(xiàn)tab切換的3種方式及切換保持數(shù)據(jù)狀態(tài)
這篇文章主要給大家介紹了關(guān)于vue實現(xiàn)tab切換的3種方式及切換保持數(shù)據(jù)狀態(tài)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05

