首页 > 其他 > 详细

vue 取消上次请求

时间:2021-06-07 23:02:56      阅读:21      评论:0      收藏:0      [点我收藏+]
<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>

vue 取消上次请求

原文:https://www.cnblogs.com/wsj1/p/14860436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!