Vue3中通过Get API请求获取Props详情及解决数据undefined问题
问题分析与解决
核心问题:API响应结构理解错误
你调用的Rick and Morty单角色接口返回的是单个角色对象,而非包含results数组的结构。代码里写的res.data.results自然会返回undefined,因为这个字段不存在。
修复步骤
修正API响应取值
将this.character = res.data.results;改为this.character = res.data;,直接获取接口返回的角色对象。修正后的
mounted钩子代码:mounted() { axios .get(`https://rickandmortyapi.com/api/character/${this.id}`) .then((res) => { this.character = res.data; // 直接取接口返回的角色对象 console.log("GET DETAIL", this.character); }) .catch((error) => { console.log(error.message); this.errored = true; }) .finally(() => (this.loading = false)); },确认id参数是否正确传递
- 若组件通过Vue Router跳转,确保路由配置已正确传递id参数:
{ path: '/character/:id', name: 'CharacterById', component: CharacterById, props: true // 开启路由参数转props } - 若通过父组件传值,确保父组件传入的
id是有效数字(比如从列表点击时传递正确的角色id)。
- 若组件通过Vue Router跳转,确保路由配置已正确传递id参数:
可选:添加参数校验
在组件props中给id添加类型校验,避免传入无效值:props: { id: { type: [String, Number], required: true }, name: String, species: String, status: String }
内容的提问来源于stack exchange,提问作者Thomas Chalanson
相关产品推荐
相关产品推荐

