首页 > 解决方案 > 使用 VueX Store 中的计算属性进行 Ajax 调用的正确方法是什么

问题描述

如何使用调用参数之一作为 VueX 中的计算状态进行 ajax 调用。例如,如果我创建 this.$axios.get('someUrl/' + accID ),accID 是来自 VueX 的计算属性(通过 MapState)。有时 id 返回“未定义”,我怀疑这是由于 axios 在从商店填充 id 数据之前发出 get 请求

我曾尝试在 Vue 组件中的“accID”上使用 watch() 来等待 accID 解决但无济于事

//部分代码

 computed: {
    ...mapState(['user']),
  },

 async fetchData() {


        const [foodData, option] = await Promise.all([
          this.$axios({
            url: `food/${this.user.accID}`,
            method: 'get',
          }),
          this.$axios({
            url: 'options',
            method: 'get',
          })
        ])

  //foodData returns undefined because user.accID is undefined (sometimes)

期待

this.$axios({ url:'food/12345', method: 'get' })

反而

this.$axios({ url:'food/undefined', method: 'get' })

标签: javascriptvue.jsvuejs2axiosvuex

解决方案


更改${user.accID}为:${this.user.accID}_url

url: `food/${this.user.accID}`,

推荐阅读