如何在Vue3中单击按钮终止axios请求

在前端开发中,我们经常会使用axios来发送网络请求。而有时候我们需要在请求尚未完成时终止请求,以节省资源或避免不必要的网络流量。在Vue3中,我们可以通过以下方法实现在单击按钮时终止axios请求。

创建Vue3项目并安装axios

首先,我们需要创建一个Vue3项目并安装axios。在命令行中执行以下命令:

vue create axios-cancel-request
cd axios-cancel-request
npm install axios
  • 1.
  • 2.
  • 3.

创建一个Button组件

接下来,我们创建一个Button组件,当用户单击按钮时,会发送axios请求。在src/components目录下创建一个Button.vue文件,代码如下:

<template>
  <button @click="fetchData">Fetch Data</button>
</template>

<script>
import { ref } from 'vue'
import axios from 'axios'

export default {
  setup() {
    const fetchData = async () => {
      try {
        const response = await axios.get('
        console.log(response.data)
      } catch (error) {
        console.error(error)
      }
    }

    return {
      fetchData
    }
  }
}
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

终止axios请求

为了在单击按钮时终止axios请求,我们可以使用axios的CancelToken。我们需要在fetchData函数中添加以下代码:

import { ref } from 'vue'
import axios from 'axios'

let cancel

export default {
  setup() {
    const fetchData = async () => {
      if (cancel) {
        cancel()
      }

      const source = axios.CancelToken.source()

      try {
        const response = await axios.get(' {
          cancelToken: source.token
        })
        console.log(response.data)
      } catch (error) {
        if (axios.isCancel(error)) {
          console.log('Request canceled:', error.message)
        } else {
          console.error(error)
        }
      }
    }

    return {
      fetchData
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.

使用Button组件

最后,我们在App.vue中使用我们创建的Button组件:

<template>
  <div>
    <Button />
  </div>
</template>

<script>
import Button from './components/Button.vue'

export default {
  components: {
    Button
  }
}
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

现在,当用户单击按钮时,会发送axios请求并在需要时终止请求。

总结

在Vue3中终止axios请求可以通过使用CancelToken实现。我们可以在发送请求前取消之前的请求,并在请求完成或取消时处理相应的逻辑。这样可以有效地管理网络请求,提高用户体验。


饼状图示例 70% 30% 饼状图示例 成功 失败

通过本文的介绍,相信您已经学会如何在Vue3中单击按钮终止axios请求。希望本文对您有所帮助,谢谢阅读!