You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3组合式API加载动态组件报错:缺少模板或渲染函数

问题原因

你的getMissionComponent是异步函数,调用后返回的是Promise对象,而Vue的<component :is="">指令要求传入实际的组件定义(组件对象/构造函数),无法识别Promise,因此会抛出「Component is missing template or render function」的错误。

直接在:is中写SimpleQuestions时,你传入的是已经导入的组件对象,符合Vue的要求,所以能正常加载。

解决方案

不要直接在:is中调用异步函数,而是提前完成异步请求,把每个任务对应的组件预加载到响应式数据中,再渲染组件:

  1. 定义响应式数组存储包含组件信息的任务列表
  2. 在组件初始化或获取任务列表后,批量请求任务信息并绑定对应组件
  3. 模板中直接使用预加载好的组件对象

修改后的代码示例:

import { ref, onMounted } from 'vue';
import SimpleQuestions from '@/components/SimpleQuestions.vue';

const templates = {
  SimpleQuestions,
};

// 原有的任务列表
const missions = ref([]);
// 存储带组件信息的任务列表
const missionsWithComponents = ref([]);

// 预加载每个任务对应的组件
const loadMissionComponents = async () => {
  const tempList = [];
  for (const mission of missions.value) {
    const missionInfo = await userStore.getMissionInfo(email.value, roomID.value, mission.name);
    tempList.push({
      ...mission,
      component: templates[missionInfo.template]
    });
  }
  missionsWithComponents.value = tempList;
};

onMounted(async () => {
  // 先获取原始任务数据(此处替换为你实际获取missions的逻辑)
  // missions.value = await yourFetchMissionsApi();
  // 再加载对应组件
  await loadMissionComponents();
});

模板部分修改为:

<div v-for="(item, index) in missionsWithComponents" :key="index">
  <component :is="item.component"></component>
</div>
额外提示
  • 你的原代码中switch语句未闭合,记得补充default分支和闭合语法,避免语法错误
  • 如果后续有更多组件,可以扩展templates对象,无需修改逻辑,直接映射组件名称即可

内容的提问来源于stack exchange,提问作者Dp258

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 23:20:07