在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渲染失效内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论