如何使用axio调用的响应来构建另一个调用的请求



这就是我当前的asyncData的样子,它使用axios调用来工作和填充eventsbooking

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
}
}

最新更新