Passing Data in asyncData Nuxt.js

只谈情不闲聊 提交于 2019-12-24 21:34:18

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/51224224/passing-data-in-asyncdata-nuxt-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!