当前位置: 代码网 > it编程>前端脚本>Vue.js > Vue3动态组件<component>渲染失效原因分析

Vue3动态组件<component>渲染失效原因分析

2024年11月25日 Vue.js 我要评论
在vue2中伪代码如下:<template> <component :is="currentactivetab.component" ref="co

在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动态组件&lt;component&gt;渲染失效原因分析的文章就介绍到这了,更多相关vue3 component渲染失效内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com