美文网首页
Vue axios请求频繁时取消上一次请求

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

作者: 子语喵 | 来源:发表于2021-03-01 10:19 被阅读0次
业务场景:会连续发送多个请求,而异步会导致最后得到的结果回显会有问题。我们使用vue的CancelToken取消上一次的请求
<script>
import axios from 'axios'
import qs from 'qs'
export default {
  methods: {
    getInfo() {
      var that = this;
      // 取消上一次请求
      this.cancelRequest()
      this.$axios.post('接口地址', '接口参数',{
        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);
        }
      })
    }
  }
}
</script>

相关文章

网友评论

      本文标题:Vue axios请求频繁时取消上一次请求

      本文链接:https://www.haomeiwen.com/subject/ftwofltx.html