3

I'm new to nuxt.js and I want to ask if there is any way to pass data in asyncData. Here is the code.

    <script type="text/javascript">
  import axios from 'axios'
  export default {
    data(){
        return {
          sample: 'asdf',
          baseUrl: 'https://jsonplaceholder.typicode.com/posts/1'
        }
    },
    async asyncData ({ params }) {
      let { data } = await axios.get(this.baseUrl)
      return { title: data}
    }
}
</script>

I know you don't have access to this but is there a way to pass data. Thanks.

6
  • pass data from where? Commented Jul 7, 2018 at 15:28
  • in the asyncData, look at this.baseUrl in axios.get(this.baseUrl) it's invalid. How can I pass it? Thanks. Commented Jul 7, 2018 at 17:03
  • 1
    you cant pass it from data. You can only use objects from context. Like params, or store. You can put anything in store and access it from asyncDAta Commented Jul 7, 2018 at 17:27
  • I see, I know now... so my global data need to pass in the store and it's accessible in the context.store or es6 { store }. Thanks.. Commented Jul 7, 2018 at 17:30
  • well. for global data you use process.env Commented Jul 7, 2018 at 18:02

1 Answer 1

5

Usually this kind of configuration like baseurl defined in env vars in nuxt. Docs

  // nuxt.config.js
  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:3000'
  }

Then you can access it anywhere via process.env e.g. in asyncData

async asyncData ({ params }) {
  let { data } = await axios.get(process.env.baseUrl)
  return { title: data}
}

But for baseUrl for axios you can just define it once e.g. in plugins/axios and then import from there

import axios from 'axios'

export default axios.create({
  baseURL: process.env.baseUrl
})

Or you can use @nuxt/axios module where u can set baseUrl as an configuration option

Sign up to request clarification or add additional context in comments.

1 Comment

You can also access env directly asyncData({ env })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.