Vue3动态组件<component>渲染失效原因分析
作者:小达不刘
在vue2中使用正常,但是迁移到Vue3中,发现组件无法渲染, 本文给大家分别展示Vue2和Vue3的代码,组件能正常在Vue2中渲染,在Vue确没有渲染出来,并通过代码示例给出了解决方法,需要的朋友可以参考下
在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渲染出来是酱紫的:

只有一个壳子,没有任何内容。
问题出在组件的名字上了:在 <script setup> 中要使用动态组件时,需要直接用 :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>
到此这篇关于Vue3动态组件<component>渲染失效原因分析的文章就介绍到这了,更多相关Vue3 component渲染失效内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
