vue+axios实现点击取消请求功能

这篇文章展示了如何在Vue.js应用中创建一个按钮,点击后触发数据导出,同时显示进度条。使用axios库进行异步请求,并通过CancelToken实现请求取消功能,当用户点击取消时,能够终止导出过程并显示相应错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述

代码片段

<template>
<el-button type="primary" @click="clickExportData">导出</el-button>

<el-dialog title="正在导出,请稍等" :visible.sync="progressShow" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" width="20%">
       <div style="text-align: center;">
           <el-progress :percentage="percentage" type="circle"></el-progress>
       </div>
       <div slot="footer">
           <el-button type="primary" @click="cancelSend">取消下载</el-button>
       </div>
   </el-dialog>
</template>
<script>
export default {
	data() {
        return {
            percentage:0, //进度条
            progressShow: false, // 是否显示进度条弹出层
            source: ''
        }
    },
    methods: {
		// 点击导出数据
        clickExportData(){
			this.progressShow = true;
            this.percentage = 0;
            let times = setInterval(() => {
                if(this.percentage == 89){
                    clearInterval(times);
                }else{
                    if(!this.percentage){
                        this.percentage = 0;
                    }
                    this.percentage++;
                }
            }, 2000);
            // 每次发送请求前先初始化CancelToken,防止在点击一次后失效的问题
            // this.$axios是在main.js中引入的axios:
            // import axios from "axios";
            // Vue.prototype.$http = axios
            const { CancelToken } = this.$axios; 
            this.source = CancelToken.source();
            this.$http.post(url, data, { cancelToken: this.source.token }).then(res => {			console.log('请求成功');
            }).catch(err => {
            	// 用户取消
                console.log(err);
                this.progressShow = false;
                if(err.message && err.message == '请求被用户取消'){
                    this.$message.error('请求已被取消!');
                }else{
                    this.$message.error('请求超时,导出数据失败!');
                }
            });
		},
		// 点击取消发送请求
        cancelSend(){
			this.source.cancel('请求被用户取消');
		}
	}
}
</script>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值