首页 > 解决方案 > 取消/中止 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 实例。

标签: javascriptvue.jsaxios

解决方案


推荐阅读