Vue项目中Axios取消请求功能实现

1,封装axios实例 request.js

const axios = require('axios');
 
// 创建一个axios实例
const service = axios.create({
  baseURL: "https://ip:port",
  timeout: 60000
});
 
export default service

2,封装请求 api.js

import service from 'request'
import axios from "axios";

export const canCancelApi = (data, cancel) => {
    return service({
        url: '/api/test',
        method: 'post',
        data,
        cancelToken: new axios.CancelToken((c) => {
            cancel && cancel(c)
        })
    })
}

3,调用api

import {onBeforeUnmount} from 'vue'
import {canCancelApi} from "api";


const apiCancel = null
// 通过回调接收caccel方法
canCancelApi(params, (cancle) => {
    apiCancel = cancle
  }).then(res => {})

onBeforeUnmount(() => {
  if(apiCancel){
    // 关闭页面时如果请求存在则取消请求
    apiCancel('custom-cancel')
  }
}

你可能感兴趣的:(前端,javascript,开发语言,vue.js)