我們在做項(xiàng)目的時候,為了防止一些用戶的瘋狂點(diǎn)擊,獲取是tab欄的快速切換,我們往往需要做一些防止重復(fù)提交的操作,好處就不用說了。請看代碼(使用的是axios)
var app = new Vue({
el: '#app',
data: {
source: null,
minutehchartid:'',
endTime:'',
startTime:'',
currentMinutehchartid:'',
currentEndTime:'',
currentStartTime:'',
},
methods: {
sendRequest() {
//如果是同一個請求就按返回,不需要重復(fù)請求
if (this.currentMinutehchartid==this.minutehchartid&& this.currentEndTime.getTime()==this.endTime.getTime()&&this.currentStartTime.getTime()==this.startTime.getTime()) {
return;
}
//防止連續(xù)點(diǎn)擊,取消上一次請求
if (this.source != '') {
this.source.cancel();
}
this.currentMinutehchartid=this.minutehchartid;
this.currentEndTime=this.endTime;
this.currentStartTime=this.startTime;
this.source = this.axios.CancelToken.source(); // 這里初始化source對象
this.axios({
method: 'post',
url: "tideInfo/getTideMinuteListPerHour",
data: {
endTime: this.endTime,
startTime:this.startTime,
tideStationId:_this.minutehchartid
},
cancelToken: _this.source.token,
})
.then(res => {
// 你的邏輯
})
.catch(res => {
// 如果調(diào)用了cancel方法,那么這里的res就是cancel傳入的信息
// 你的邏輯
if (this.axios.isCancel(response)) {
console.log('Request canceled', response.message);
} else {
this.$message({
type: 'info',
message: '服務(wù)器錯誤!'
});
}
})
},
}
})
這樣,隨便你怎么瘋狂地點(diǎn)擊,只要上一個請求沒有返回結(jié)果,再次請求的話,就會取消上一個請求,執(zhí)行當(dāng)前請求。