javascript - 取消/中止 Vue 组件上的 Axios 帖子
问题描述
我有一个 Vue 组件,它有一个值列表,当您选择这些值时,这会更改所选数组,该数组实际上会发布到端点。
如果用户垃圾邮件单击这些值,我会遇到问题,因为每次更改都会创建一个单独的帖子,我想要这样,如果用户选择另一个项目,那么当前待处理的帖子将被取消,因此新值会被发布并更新具有两个选定项目的端点。
但是我在中止当前的 axios 请求时遇到问题,我提供了下面的代码。没有错误,请求根本不会取消。
export default {
props: {
endpoint: {
default: '',
type: String
},
parameters: {
default: null,
type: Object
}
},
data: () => ({
loaded: false,
selected: [],
save: [],
data: [],
cancel: undefined
}),
methods: {
update() {
const self = this;
let params = this.parameters;
params.data = this.selected;
this.$root.$emit('saving', {
id: this._uid,
saving: true
});
if (self.cancel !== undefined) {
console.log('cancel');
this.cancel();
}
window.axios.post(this.endpoint + '/save', params, {
cancelToken: new window.axios.CancelToken(function executor(c) {
self.cancel = c;
})
}).then(() => {
this.$nextTick(() => {
this.loaded = true;
this.$root.$emit('saving', {
id: this._uid,
saving: false
});
});
}).catch(function (thrown) {
if (window.axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
}
});
}
}
}
我在我的 Vue 应用程序上创建了一个全局 Axios 实例。
解决方案
推荐阅读
- java - 使用 Guava 的 Tables.toTable
- jquery - 更改文本框的最大长度值
- node.js - Windows Bash 脚本在不执行所有命令的情况下退出
- c - GCC C 并将整数传递给 PostgreSQL
- excel - Excel - 文本或数字公式
- ssis-2012 - 将 DT_WSTR 转换为 DT_DATE
- ios - 有大量单元格时删除和插入行崩溃
- c# - 禁用 chrome 作为多进程。Chrome 版本 68 无法捕获 URL
- facebook - 无法读取未定义的属性“logInWithReadPermissions”,但存在 LoginManager
- jpa - 为什么在看到 PersistentBag 的实体中使用 JPA 列出(@OneToMany)