vue项目关于循环调接口的相关问题

问题遇到的现象和发生背景

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}创建失败`,
                      });
                    }
              }
            });
      }
      }

你说的优化是指什么,只弹一次吗?

你如果想弄成只显示一个弹窗,然后一直显示到循环请求全部结束,可以这样:

  1. 用标签形式的组件,用变量控制其显隐,或者用提示组件的单例模式
  2. 在foreach循环里,id判断索引,第一次成功后让组件显示,然后最后一次成功使其隐藏(index = arr.length-1)

但是,你这种设计思想本身就很不好,如果你是数组里要多次创建数据,最好是让后端修改接口,改成可以传多组数据的,前端循环请求太多的话可能会造成网络阻塞或者超时等等问题。

如有帮助,麻烦点个【采纳此答案】