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)文章希望大家以后多多支持腳本之家!
vue項目前端微信JSAPI與外部H5支付相關(guān)實現(xiàn)過程及常見問題
使用vue-cli創(chuàng)建vue2項目的實戰(zhàn)步驟詳解
詳解auto-vue-file:一個自動創(chuàng)建vue組件的包
npm install -g @vue/cli安裝vue腳手架報錯問題(一般都能解決)

