问题
用户重复点击发送请求,由于请求速度较慢,导致多次请求的数据在同一个弹窗中显示,数据不匹配。
解决方法
Axios文档中提供了取消请求的方法,cancel token API
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelToken
constructor:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
Note: you can cancel several requests with the same cancel token.
项目实例
import axios from "axios";
import { Vue, Component, Watch } from "vue-property-decorator";
const CancelToken = axios.CancelToken;
@Component
export default class LayerControlMixins extends Vue {
private cancel: any = null;
// 点击事件函数
private bindClickQuery() {
// 判断并取消上次请求
if (this.cancel) {
this.cancel();
}
let that = this
// 触发请求
axios
.post(url, JSON.stringify(params), {
cancelToken: new CancelToken(function executor(c) {
that.cancel = c;
})
})
.then((res: any) => {
console.log(res)
// ...
}
}
}
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!