Axios provides the axios.CancelToken.source().cancel() method to cancel the request being sent, we can use this to process
- Simple api package, depending on the package method of the company project
import axios from 'axios'
export function getDataList (cancelToken) {
return axios({
method: 'get',
url: 'http://xxx.xxx.x.x:4399/getList',
cancelToken
})
}
- Send a request in the vue component, cancel the request being sent
<template>
<div>
<el-button @click="handleGetData">发送请求</el-button>
<el-button @click="handleCancel">取消请求</el-button>
</div>
</template>
<script>
import {
getDataList } from './request'
import axios from 'axios'
export default {
data() {
return {
source: null
}
},
methods: {
async handleGetData() {
const source = axios.CancelToken.source()
this.source = source
try {
const res = await getDataList(source.token)
console.log(res)
} catch (error) {
}
},
handleCancel() {
this.source.cancel('取消请求')
}
}
}
</script>