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>