vue 取消上次请求

<script>
import axios from 'axios'
import qs from 'qs'

export default {
    methods: {
        request(keyword) {
            var that = this;
            var CancelToken = axios.CancelToken
            var source = CancelToken.source()
              
            // 取消上一次请求
            this.cancelRequest();
            
            axios.post(url, qs.stringify({kw:keyword}), {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json'
                },
                cancelToken: new axios.CancelToken(function executor(c) {
                    that.source = c;
                })
            }).then((res) => {
                // 在这里处理得到的数据
                ...
            }).catch((err) => {
                if (axios.isCancel(err)) {
                    console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message
                } else {
                    //handle error
                    console.log(err);
                }
            })
        },
        cancelRequest(){
            if(typeof this.source ==='function'){
                this.source('终止请求')
            }
        },
    }
}
</script>
原文地址:https://www.cnblogs.com/wsj1/p/14860436.html