api 使用用户 ID 调用

api call using userid

我需要拨打 api 电话以获得用户推荐。这是我的 api url: http://URL/../../patients/用户 ID/recommendations

我的用户 ID 保存在我的 vuex 存储中的文件 "patient.module.js:

state: {
    id: null,
    email: null,
    password: null,
    location: [],
    specialty: [],
    attribute: [],
    language: [],
    gender: [],
    editUser: false,
  },
  getters: {
    getUserId(state) {
      return state.id;
    },
  },

我的商店结构如下所示:

在我的 RecommendationView 中,我尝试显示来自 api 调用的 json 响应。 在这里,我编写了调用 api 的方法。

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

很遗憾,我收到此错误:未定义 id' 如何从商店获取患者 ID 并将其与我的请求一起发送? 提前致谢!

你可以在这样的计算中使用mapState

<script>
  import {mapState} from "vuex";


export default {
  computed: {
    ...mapState({
      user: state => state.patient
    })
  },
  data() {},
  methods: {
    getRecommendations() {
      this.id = this.user.id;
      return http
        .get(`/patients/${id}/recommendations`)
        .then((response) => {
          this.recommendation = response.data;
          console.log(response);
        })
        .catch((error) => {
          console.log(
            "Ein Fehler beim User ist aufgetreten: " + error.response
          );
        });
    },
  }
} 
</script>