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

Vue项目从Vuex获取patient ID调用推荐接口报id未定义如何解决

报错原因

id is not defined的根本原因是:你将从Vuex取到的用户ID赋值给了组件实例属性this.id,但在请求路径的模板字符串中直接调用了未声明的局部变量id,缺少this指向组件实例。
另外如果你的patient.module.js是开启了命名空间的Vuex模块,原代码的getter调用方式也需要调整。

修正代码

方案1:直接取值拼接路径(无需额外存储id到组件)

methods: {
  getRecommendations() {
    // 未开启命名空间的模块调用方式
    const userId = this.$store.getters.getUserId
    // 若patient模块开启了命名空间,替换为下面的写法
    // const userId = this.$store.getters['patient/getUserId']
    
    // 可选:提前判断id是否存在,避免无效请求
    if (!userId) return console.log('用户ID未获取到')

    return http
      .get(`/patients/${userId}/recommendations`)
      .then((response) => {
        this.recommendation = response.data;
        console.log(response);
      })
      .catch((error) => {
        console.log(
          "Ein Fehler beim User ist aufgetreten: " + error.response
        );
      });
  },
}

方案2:保留原赋值逻辑,补充this指向

methods: {
  getRecommendations() {
    // 注意命名空间适配,开启命名空间时用this.$store.getters['patient/getUserId']
    this.id = this.$store.getters.getUserId
    return http
      // 模板字符串中调用组件实例属性需要加this
      .get(`/patients/${this.id}/recommendations`)
      .then((response) => {
        this.recommendation = response.data;
        console.log(response);
      })
      .catch((error) => {
        console.log(
          "Ein Fehler beim User ist aufgetreten: " + error.response
        );
      });
  },
}

命名空间判断方式

打开patient.module.js文件,若导出的模块配置中存在namespaced: true,则说明该模块开启了命名空间,需要使用['模块名/getter名']的格式调用getter。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:45:03