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

2021-03-01  本文已影响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>
上一篇 下一篇

猜你喜欢

热点阅读