Vue+axios interrupts the request being sent

Axios provides the axios.CancelToken.source().cancel() method to cancel the request being sent, we can use this to process

  1. 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 // 需要设置cancelToken字段,用于取消请求使用
  })
}

  1. 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>
// 这里为了方便直接将axios导入了,其实可以在封装api的时候做一下处理可能会更好
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
      // source接收的是axios内部提供用于取消请求的方法
      // 我个人的理解是,每一个请求都有对应自己的token,axios通过这个去取消对应的请求
      try {
    
    
        const res = await getDataList(source.token)
        console.log(res)
      } catch (error) {
    
    
        // console.log(error)
      }
    },
    // 取消请求
    handleCancel() {
    
    
      this.source.cancel('取消请求')
      // cancel内的取消请求可以当成是取消请求后抛出的提示文案,可打印this.source.cancel('取消请求')看看
    }
  }
}
</script>

Guess you like

Origin blog.csdn.net/qq_35695023/article/details/114083666