vue3 动态组件component不生效问题

问题: vue3循环渲染动态组件component不生效,页面空白

在vue3使用component动态组件展示组件时,组件就是不展示显示空白。在vue2中使用动态变量component展示组件都是没问题。试了很多方法 踩了很多坑,所以记录下:

  <div class="preview-list" id="canvas-area">
    <component
      v-for="component in components" 
      :key="component.id"
      :is="component.name"
      v-bind="component.props" 
      />
  </div>
<script setup lang="ts">
import LText from '@/components/LText'
import { ref } from 'vue'
interface styleProps = {
   text: string;
   fontSize: string;
}
interface componentData = {
  id: number;
  name: string;
  props?: styleProps;
}
const components = ref<componentData[]>([
    { id: 1, name: 'LText', props: { text: 'hello', fontSize: '12px'}},
    { id: 2, name: 'LText', props: { text: 'hello2', fontSize: '14px'}},
    { id: 3, name: 'LText', props: { text: 'hello3', fontSize: '16px'}}
])
</script>

因为vue3使用的是setup语法,组件只要import导入就行 不需要再像vue2中在components挂载,这样导致我想渲染的组件是没有渲染出来页面出现空白,尝试了很多办法对应的组件里面添加多个script指定对应的组件名,还是没生效

解决方法

使用shallowReactive或者shallowRef把对应的组件名称重新定义下,遍历component时,is采用对象key获取对应的对应的组件,这样组件就显示出来了

  <div class="preview-list" id="canvas-area">
    <component
      v-for="component in components" 
      :key="component.id"
      :is="componentsName[component.name]"
      v-bind="component.props" 
      />
  </div>
<script setup lang="ts">
import LText from '@/components/LText'
import { ref, shallowReactive } from 'vue'
interface styleProps = {
   text: string;
   fontSize: string;
}
interface componentData = {
  id: number;
  name: string;
  props?: styleProps;
}
type componentName = {
  [key: string]: any
}
const components = ref<componentData[]>([
    { id: 1, name: 'LText', props: { text: 'hello', fontSize: '12px'}},
    { id: 2, name: 'LText', props: { text: 'hello2', fontSize: '14px'}},
    { id: 3, name: 'LText', props: { text: 'hello3', fontSize: '16px'}}
])
// 解决方案
const componentsName = shallowReactive<componentName>({
  LText
})

</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值