在 asyncData Nuxt.js 中传递数据 [英] Passing Data in asyncData Nuxt.js
问题描述
我是 nuxt.js 的新手,我想问一下是否有任何方法可以在 asyncData 中传递数据.这是代码.
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>
我知道您无权访问this
,但是有没有办法传递数据.谢谢.
I know you don't have access to this
but is there a way to pass data. Thanks.
推荐答案
通常这种配置,比如在 nuxt 的 env vars 中定义的 baseurl.文档
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'
}
然后你可以通过 process.env 在任何地方访问它,例如在异步数据中
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}
}
但是对于 axios 的 baseUrl,您可以只定义一次,例如在 plugins/axios 中,然后从那里导入
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
})
或者您可以使用 @nuxt/axios 模块,您可以在其中将 baseUrl 设置为配置选项
Or you can use @nuxt/axios module where u can set baseUrl as an configuration option
这篇关于在 asyncData Nuxt.js 中传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!