【问题标题】:How to pass to axios a Vuex variable using Nuxt.js?如何使用 Nuxt.js 将 Vuex 变量传递给 axios?
【发布时间】:2019-12-31 18:33:30
【问题描述】:

我实际上在 Nuxt.js 项目中使用 Axios 来捕获 Json 文件以将其显示在我的网站上。我想在 Vuex 中使用变量存储来选择我的 Axios 获取请求的路径。

这是我的<script> 的样子:

<script>
import axios from 'axios'
import vuex from 'vuex'

export default {

  async asyncData({ }) {
    const json = await axios.get(`https://myurl.com/${$store.getters["getPath"]}`)
    return { json }
  }
}
</script>

很确定这不是一个好方法。我收到控制台错误:ReferenceError: store is not defined

提前致谢!

【问题讨论】:

    标签: axios vuex nuxt.js


    【解决方案1】:

    使用asyncData 方法时,您无权访问this 关键字,因此asyncData 方法接收context 对象作为参数,您可以从中访问Axios、Vuex 等。因此你不需要导入 Axios 和 Vuex。

    export default {
      async asyncData({ $axios, store }) { //here we get Axios and Vuex
        const json = await $axios.get(`https://myurl.com/${store.getters["getPath"]}`)
        return { json }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 1970-01-01
      • 2020-04-02
      • 2019-08-28
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      相关资源
      最近更新 更多