一、问题
之前一般都是这样调用接口的,在调用a接口访问成功之后的返回体里面调用b接口,这样就能实现按顺序调用两个接口,例如下面这种写法:
init(){
let id = this.$router.currentRoute.params.id;
let data = StoreService.getChildMenu(id);
this.$data.loading = true;
this.$api.req("/wiringDiagram/buttonInfo", {
stationId: data.electricityStation.sysId
},res => {
this.$data.buttonList = res.data;
this.$api.req("/wiringDiagram/mainRealTime", {
stationId: data.electricityStation.sysId,
ceKon:this.$data.buttonList[4].buttonId,
ceKon2:this.$data.buttonList[3].buttonId,
ceKon110Kv:this.$data.buttonList[0].buttonId,
segmented35kv:this.$data.buttonList[7].buttonId,
inLine1:this.$data.buttonList[20].buttonId,
}
,res => {
this.$data.loading = false;
this.$data.ceKon110Kv=res.data.ceKon110Kv;
},res => {
this.$message.error(res.msg)
this.$data.loading = false;
})
this.$data.loading = false;
},
res => {
this.$message.error(res.msg)
this.$data.loading = false;
})
},
但是我的一个需求就是要一直定时调用b接口,而a接口返回的数据正是b接口需要的,a接口只需要调用一次即可。如果这种写法的话,就会每次同时调用a、b接口,造成时间性能的消耗。
因此,需要把这两个方法拆开。
二、用函数传递来实现
思想:在调用a接口的时候,传入一个函数形参,然后再调完接口后,再执行这个函数。
写法:
1、在a方法中传入形参函数fun ,然后在返回结果后面实现fun()函数
init(fun){
let id = this.$router.currentRoute.params.id;
let data = StoreService.getChildMenu(id);
this.$data.loading = true;
this.$api.req("/wiringDiagram/buttonInfo", {
stationId: data.electricityStation.sysId
},res => {
this.$data.buttonList = res.data;
fun();
this.$data.loading = false;
},res => {
this.$message.error(res.msg)
this.$data.loading = false;
})
},
2、在调用a方法的时候,传入b方法。然后就可以实现调用的接口顺序了,且a方法只需要执行一次。
mounted(){
let _this = this;
this.init(() =>{
_this.realTime();
})
},