Vue3中v-for循环遍历<component></component>引入的组件为何未能加载?
在vue3中,使用v-for循环遍历的方式<component></component>无法加载组件
<template>
<div>
<div v-for="item in comList " :key="item.id">
<component :is="item.comName" />
</div>
</div>
</template>
<script setup>
import OneCom from "./one-com";
import {ref} fromm vue;
const comList = ref([{id: 1,comName:"OneCom "}])
</script>
如果不通过遍历能正常加载出组件
<template>
<div>
<component is="OneCom" />
</div>
</template>
<script setup>
import OneCom from "./one-com";
import {ref} fromm vue;
const comList = ref([{id: 1,comName:"OneCom "}])
</script>
回复
1个回答
test
2024-06-20
将组件本身传递给 is 而不是其名称,则不需要注册:
import OneCom from './one-com.vue'
import { ref, markRaw } from 'vue'
const comList = ref([{ id: 1, comName: markRaw(OneCom) }])
如果想通过名称传递则必须先对其进行注册:
<script setup>
import OneCom from './one-com.vue'
import { defineComponent, ref } from 'vue'
const comList = ref([{ id: 1, comName: 'OneCom' }])
</script>
<script>
export default defineComponent({
components: { OneCom }
})
</script>
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容