Search code examples
axiosvuexnuxt.js

How to pass to axios a Vuex variable using Nuxt.js?


I actually using Axios in a Nuxt.js project to catch Json file to display it on my website. I would like to use a variable store in Vuex to select the path for my Axios get request.

Here's what my <script> looks like:

<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>

Pretty sure that isn't the good method to do it. I receive the console error : ReferenceError: store is not defined.

Thanks in advance!


Solution

  • While using the asyncData method you don't have access to this keyword so the asyncData method receives the context object as an argument from which you can get access to Axios, Vuex etc. And thus you don't need to import Axios and 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 }
      }
    }