当前位置: 首页 > news >正文

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>

相关文章:

  • 深度学习(一)-感知机+神经网络+激活函数
  • Ollydbg提示:xxxxxx可能不是一个 32 位 PE 文件,无论如何都尝试载入吗?
  • 十一. 常用类
  • 【C++】C++ 多态的底层实现
  • pyautogui对鼠标的几种操作,附代码示例
  • 永劫无间:欺骗振刀+快速取消蓝色霸体+升龙+追击+下劈
  • mysql集群技术
  • 20-22 - 打造专业的编译环境
  • 人该怎样活着呢?48
  • Vue3 官方推荐状态管理库Pinia
  • 全球1km分辨率人口分布栅格数据
  • 2024国赛数学建模评价类算法解析,2024国赛数学建模C题思路模型代码解析
  • 【PGCCC】揭秘PostgreSQL中行存储索引的奥秘:从原理到实战案例
  • ping不通本地虚拟机的静态ip的解决方案
  • 前端知识HTMLCSS
  • 算法-初阶
  • 【科研绘图】【条形图地图】【饼图地图 】:附Origin详细画图流程
  • 全面解析NVIDIA显卡:从入门级到旗舰级显卡详解
  • 线性约束最小方差准则(LCMV)波束形成算法及MATLAB深入仿真分析
  • yolo8 目标检测、鉴黄
  • 从孔雀尾巴到蒙娜丽莎,一个鸟类学博士眼中的“美”
  • 李在明涉嫌违反《公职选举法》案将于5月1日宣判
  • 一位排球青训教练的20年时光:努力提高女排球员成才率
  • 长三角铁路“五一”假期运输今启动:预计发送旅客量增6%,5月1日当天有望创新高
  • 自称“最美”通缉犯出狱当主播?央广网:三观怎能跟着“五官”跑
  • 4月份全国93个国家气象站日最高气温达到或突破极值