【问题标题】:Vuex and Axios in asyncDataasyncData 中的 Vuex 和 Axios
【发布时间】:2019-12-06 02:25:23
【问题描述】:

我想在 asyncData 中访问我的 Vuex 数据,但我不能。另外我似乎无法在 asyncData 中使用 axios 模块。

我尝试了很多。

pages/index.vue

export default {
  asyncData() {
    //in my project there's a lot more code here but i think this is enough 
    let id = this.$store.state.id //i know i should prob use getter but no
    //here i want to do an axios req with this var "id" but axios doesnt work
    return axios.get(`url${id}`)
      .then(...) //not gonna write it out here
  }
}

store/index.js

export const state = () => ({
  id: "#5nkI12_fSDAol/_Qa?f"
})

我希望它从 Vuex 获取 ID,然后执行 Axios req。整个应用程序不起作用。

【问题讨论】:

    标签: javascript nuxt.js


    【解决方案1】:

    您不能在 asyncData 中使用 this。函数 asyncData 被传递了一个 context 对象作为参数,它基本上代表了 this 关键字。
    首先,您需要指定要从 context 对象中检索的内容,然后您就可以使用它了。

    在您的情况下,请执行以下操作:

    export default {
      asyncData({ $axios, store }) { //here we get Vuex and Axios
        let id = store.state.id
        return $axios.get(`url${id}`)
          .then(...)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2019-08-21
      • 2020-01-05
      • 2020-08-17
      • 1970-01-01
      相关资源
      最近更新 更多