Vue3 TSX中使用动态组件报错:无法解析组件的问题咨询
Vue3 TSX中动态组件报错的解决方法
问题原因
Vue模板语法里的<component>是专属语法糖,TSX语法并不识别这个标签,直接使用会触发组件解析失败的报错。
解决方法
在TSX中需要通过Vue提供的h函数来渲染动态组件,以下分两种场景给出实现方式:
场景1:直接使用已导入的组件
如果动态渲染的是已经导入的组件实例,直接用h函数创建节点:
<script lang="tsx"> import { defineComponent, h, ref } from 'vue'; import { NInput, NSelect } from 'naive-ui'; export default defineComponent({ setup(props) { const list = ref([ { comp: NInput }, { comp: NSelect } ]); return () => ( <n-form> {list.value.map((item, idx) => ( <n-form-item key={idx}> {/* 用h函数渲染动态组件,第二个参数可传递组件props */} {h(item.comp, { placeholder: '请输入内容' })} </n-form-item> ))} </n-form> ); } }); </script>
场景2:通过组件名称字符串映射渲染
如果是从后端或配置中获取组件名称字符串,先建立名称与组件实例的映射表,再通过h函数渲染:
<script lang="tsx"> import { defineComponent, h, ref } from 'vue'; import { NInput, NSelect, NCheckbox } from 'naive-ui'; // 建立组件名称到实例的映射表 const componentMap = { 'n-input': NInput, 'n-select': NSelect, 'n-checkbox': NCheckbox }; export default defineComponent({ setup(props) { const list = ref([ { compName: 'n-input' }, { compName: 'n-select' } ]); return () => ( <n-form> {list.value.map((item, idx) => { const TargetComp = componentMap[item.compName]; // 处理不存在的组件,避免报错 if (!TargetComp) return null; return ( <n-form-item key={idx}> {h(TargetComp, { placeholder: '请输入/选择' })} </n-form-item> ); })} </n-form> ); } }); </script>
注意事项
- 确保所有需要渲染的组件都已正确导入,未导入的组件会导致渲染失败
- 动态渲染时务必添加唯一的
key值,避免列表渲染的性能问题和异常
内容的提问来源于stack exchange,提问作者laterday
相关产品推荐
相关产品推荐

