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

Vue3中通过Get API请求获取Props详情及解决数据undefined问题

问题分析与解决

核心问题:API响应结构理解错误

你调用的Rick and Morty单角色接口返回的是单个角色对象,而非包含results数组的结构。代码里写的res.data.results自然会返回undefined,因为这个字段不存在。

修复步骤

  1. 修正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));
    },
    
  2. 确认id参数是否正确传递

    • 若组件通过Vue Router跳转,确保路由配置已正确传递id参数:
      {
        path: '/character/:id',
        name: 'CharacterById',
        component: CharacterById,
        props: true // 开启路由参数转props
      }
      
    • 若通过父组件传值,确保父组件传入的id是有效数字(比如从列表点击时传递正确的角色id)。
  3. 可选:添加参数校验
    在组件props中给id添加类型校验,避免传入无效值:

    props: {
      id: {
        type: [String, Number],
        required: true
      },
      name: String,
      species: String,
      status: String
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:55:46