本文主要是介绍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')}
}
这篇关于Vue项目中Axios取消请求功能实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!