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