我想访问 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。整个应用程序无法运行。
最佳答案
您不能在 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(...)
}
}
关于javascript - asyncData 中的 Vuex 和 Axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57242101/