欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue项目中取消axios请求

程序员文章站 2022-07-09 12:47:34
...

axios中文文档
请求文件中

//构造函数来创建 cancel token
import request from '@/utils/request'
import axios from 'axios'
const CancelToken = axios.CancelToken;
export function fetchList(query,that) {
  return request({
    url: '/vue-element-admin/article/list',
    method: 'get',
    params: query,
    cancelToken: new CancelToken(function executor(c) {
      // executor 函数接收一个 cancel 函数作为参数
      that.cancel = c;
    })
  })
}
//console.log(qs.stringify({
  //name:'hana',
  //age:'18'
//}))
// logs name=hana&age=18

实际引用

  created() {
    this.getList();
    setTimeout(() => {
      this.cancel("取消了请求");
    });
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery, this)
        .then(response => {
          this.list = response.data.items;
          this.total = response.data.total;
          // Just to simulate the time of the request
          this.listLoading = false;
        })
        .catch(err => {
          console.log(err);
        });
    }
 }

效果
vue项目中取消axios请求
也可以参考混入到全局中取消请求