Vuex and Axios in asyncData

流过昼夜 提交于 2019-12-24 00:26:21

问题


I want to access my Vuex data in asyncData but I can't. Also I can't seem to be able to use axios module in asyncData.

I tried a lot.

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"
})

I expect it to get the ID from Vuex and then do a Axios req. Whole app doesn't work.


回答1:


You can't use this in asyncData. The function asyncData gets passed a context object as param which basically represents the this keyword.
First you need to specify what do you want retrieve from the context object and then you can use it.

In your case do something like this:

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


来源:https://stackoverflow.com/questions/57242101/vuex-and-axios-in-asyncdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!