vue axios请求频繁时取消上一次请求

一、前言

在项目中经常有一些场景会连续发送多个请求,而异步会导致最后得到的结果不是我们想要的,并且对性能也有非常大的影响。例如一个搜索框,每输入一个字符都要发送一次请求,但输入过快的时候其实前面的请求并没有必要真的发送出去,这时候就需要在发送新请求的时候直接取消上一次请求。

二、代码


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

export default {
    methods: {
        request(keyword) {
            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://segmentfault.com/a/1190000016963943

猜你喜欢

转载自www.cnblogs.com/lalalagq/p/10124640.html