axios参考文档:https://www.axios-http.cn/docs/cancellation
注:使用mock模块,模拟接口数据,个人测试,是无法取消请求的。
配置axios
// axios.get(url, config)
// 如果有参数 axios.get(url , { params })
export const getAxios = (url, params, config = {}) => {
config.params = params
// service 就是配置的拦截器
return service.get(url, config)
}
封装请求api
import service from '@utils/request'
import { getAxios } from '@/utils/request'
export const testApi = {
getBlogCategoryList: (params, source) => {
return getAxios('blog/getBlogCategoryList', params, { cancelToken: source ? source.token : '' })
},
// getBlogCategoryList: (params, source) => {
// return service({
// url: 'blog/getBlogCategoryList',
// method: 'get',
// params: params,
// cancelToken: source ? source.token : ""
// })
// },
}
组件内调用
import axios from 'axios'
import { testApi } from '@/api/test'
export default {
data () {
return {
source: ''
}
},
methods: {
async getList() {
// 使用 CancelToken.source 工厂方法创建一个 cancel token
let CancelToken = axios.CancelToken
let source = CancelToken.source()
this.source = source
try {
const res = await testApi.getList({}, this.source)
} catch (err) {
if (axios.isCancel(err)) {
// 处理取消请求
console.log('Request canceled:', err.message)
} else {
// 处理错误
console.log(err)
}
}
},
cancelRequest(){
setTimeout(() => {
console.log('2s')
this.source.cancel('取消请求')
}, 2000)
}
},
mounted() {
this.getList()
this.cancelRequest()
}
}
标签:axios,return,请求,取消,source,params,url,CancelToken From: https://www.cnblogs.com/naturl/p/16621222.html