javascript - asyncData 中的 Vuex 和 Axios

标签 javascript nuxt.js

我想访问 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/

相关文章:

javascript - Typescript find 无法识别返回的类型

javascript - 为什么 Javascript 规范设计者在 promise 中引入了 microtask

vue.js - Nuxt.js npm run generate 后找不到文件

vue.js - Vue/Nuxt 页面转换不起作用

javascript - checkin Nuxt Asyncdata 后重定向

javascript - 如何使用 ViewModel 连接启用复选框

javascript - 注入(inject)服务未定义

javascript - Jquery 可排序。在选中/拖动时调整 CSS

vue.js - Nuxt.js - 使用参数向 URL 添加尾部斜杠

javascript - Nuxt.js: "don' 的含义是忘记在父组件(.vue 文件)中写入。”