这就是我当前的asyncData
的样子,它使用axios调用来工作和填充events
和booking
async asyncData({ params, app }) {
const events = await app.$api.event.index(app.i18n.locale)
const booking = await app.$api.event.getByPath(
app.i18n.locale,
params.detail
)
return {
events,
booking
}
},
但我需要在数据中添加另一个对象registration
,它需要一个booking
值来生成axios url。
我试过booking
的承诺
async asyncData({ params, app }) {
let registration;
const events = await app.$api.event.index(app.i18n.locale)
const booking = await app.$api.event.getByPath(
app.i18n.locale,
params.detail
) .then((result) => {
registration = app.$api.event.getRegitrations(
app.i18n.locale,
result.id
)
});
return {
events,
booking,
registration
}
},
但这样booking
是空的,registration
的值为[object Promise]
(即使我在开发工具中看到了两个axios响应(
我怎样才能做到这一点?
尝试将registration
定义为数据属性,然后监视booking
属性,并在booking
可用时更新registration
data(){
return{
registration:null
}
},
watch:{
booking:{
handler(newVal){
if(newVal && newVal.id){
this.$api.event.getRegitrations(
this.i18n.locale,// or this.$i18n
newVal.id
).then(res=>{
this.registration=res.data
})
}
},
deep:true,
immediate:true
}
},
async asyncData({ params, app }) {
const events = await app.$api.event.index(app.i18n.locale)
const booking = await app.$api.event.getByPath(
app.i18n.locale,
params.detail
)
return {
events,
}
},
我不知道你在http调用中使用了什么,但是,如果你使用axios
,你可以得到这样的数据。
const booking = await app.$api.event.getByPath(
app.i18n.locale,
params.detail
) .then((response) => {
registration = app.$api.event.getRegitrations(
app.i18n.locale,
response.data.id
)
});
等待调用是一个承诺,它在执行异步函数的其余代码之前首先得到解析。因此,在尝试分配给booking
之前,您已经可以访问变量events
的结果。如果await
用于booking
,则可以读取变量并使用它来编写下一个Axios调用。
async asyncData({ params, app }) {
const events = await app.$api.event.index(app.i18n.locale);
const booking = await app.$api.event.getByPath(
app.i18n.locale,
params.detail
);
const registration = await app.$api.event.getRegitrations(
app.i18n.locale,
booking.id
)
return {
events,
booking,
registration
}
}