vue项目中需要在表单里动态填多组数据,需要每一组数据去调接口,现在的情况是,比如填两组数据,会有两个这样的成功弹窗,怎么做一下优化?
methods:{
//提交表单数据
addFormData(){
this.booksForm.booksInfo.forEach(item=>{
//postbooks是封装好的axios请求
postbooks({ ...item }).then((res) => {
if (res.data.result) {
this.$notify.success({
title: "成功",
message: "新建成功!"
});
};
//重新加载数据
this.onSubmit();
} else {
this.$notify.error({
title: "错误",
message: res.data.message,
});
}
});
})
}
});
}
}
methods:{
//提交表单数据
async addFormData(){
const isAllTrue = []
for(let i=0;i<this.booksForm.booksInfo.length;i++){
//postbooks是封装好的axios请求
await postbooks({ ...this.booksForm.booksInfo[i] }).then((res) => {
if(!res.data.result){
isAllTrue.push(res.data)
}
});
})
if (isAllTrue.length==0) {
this.$notify.success({
title: "成功",
message: "新建成功!"
});
};
//重新加载数据
this.onSubmit();
} else {
let errorMsg = isAllTrue.map(item=>item.message)
this.$notify.error({
title: "错误",
message: `项目${errorMsg}创建失败`,
});
}
}
});
}
}
你说的优化是指什么,只弹一次吗?
你如果想弄成只显示一个弹窗,然后一直显示到循环请求全部结束,可以这样:
但是,你这种设计思想本身就很不好,如果你是数组里要多次创建数据,最好是让后端修改接口,改成可以传多组数据的,前端循环请求太多的话可能会造成网络阻塞或者超时等等问题。
如有帮助,麻烦点个【采纳此答案】