1,封装axios实例 request.js
javascript
const axios = require('axios');
// 创建一个axios实例
const service = axios.create({
baseURL: "https://ip:port",
timeout: 60000
});
export default service
2,封装请求 api.js
javascript
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
javascript
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')
}
}