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

Vue向子组件传Typescript对象时渲染失败,属性值为undefined

解决方案

1. 修正API响应的提取逻辑

服务器返回的是包含data数组和metadata的对象,但当前API方法直接返回了res.data(即整个响应对象),导致courses被赋值为{data: [...], metadata: "none"}而非课程数组。需要修改API方法,返回res.data.data:

export const api = {
    async getAllCourses(): Promise<Course[]> {
        const res = await request.get<{ data: Course[], metadata: string }>("/v1/courses");
        console.log(res.data.data) // 现在打印的是正确的课程数组
        return res.data.data
    },
}

2. 规范子组件的Props类型定义

使用Typescript语法定义Props,既可以获得类型提示,也能确保传入的参数符合类型要求:

<script setup lang="ts">
import { useRouter } from 'vue-router'
import type { Course } from '@/path/to/your/CourseInterface' // 导入Course接口

const props = defineProps<{
    course: Course
}>();

console.log(props.course.title); // 现在可以正确访问title

const router = useRouter();

const showDetails = () => {
    router.push({name: 'courseDetails'})
}
</script>

3. 避免使用index作为v-for的key

使用课程的objectId作为key,比index更稳定,避免组件复用导致的异常:

<template>
    <!-- ... -->
    <div class="md:grid-cols-2 lg:grid-cols-1 col-gap-2 md:col-gap-8 md:row-gap-10" v-for='course in courses' :key="course.objectId">
        <Course :course="course"/>
    </div>
    <!-- ... -->
</template>

4. 添加加载状态(可选)

为了避免初始渲染时courses为空数组导致的无意义渲染,可以添加加载状态:

<script setup lang="ts">
const courses = ref<Course[]>([]);
const isLoading = ref(true);

api.getAllCourses().then(c => {
    courses.value = c;
    isLoading.value = false;
})
</script>

<template>
    <div v-if="isLoading">加载中...</div>
    <div v-else class="flex grid-cols-2 justify-start">
        <!-- 原渲染内容 -->
    </div>
</template>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:53:13