代码片段
<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>