1.封装组件
在config/setting.js中封装
fetchDownload(url, name = null) {
let anchor = document.createElement('a');
document.body.appendChild(anchor);
let headers = new Headers();
let filename = '';
headers.append('Authorization', this.takeToken());
fetch(url, { headers })
.then(response => {
filename = name ? name :
response.headers.get('Content-Disposition') ?
response.headers.get('Content-Disposition').split('=')[1] :
randstr();
return response.blob();
})
.then(blobby => {
let objectUrl = window.URL.createObjectURL(blobby);
anchor.href = objectUrl;
anchor.download = name === null ? decodeURI(filename) : filename;
anchor.click();
window.URL.revokeObjectURL(objectUrl);
document.body.removeChild(anchor);
});
},
然后在需要的页面调用
import setting from '@/config/setting'
绑定点击导出
<a-button type="primary" size="small" class="ant-link" @click.prevent="exportExcel">导出</a-button>
导出
/**
* 导出模板
*/
const exportExcel = async() => {
//调用封装好的方法进行必选参数校验
if(!checkForm()) return
let params = {
companyId: setting.takeGroupId(),
searchBeginTime: data.formData.searchBeginTime,
searchEndTime: data.formData.searchEndTime,
orgCodeList: data.formData.orgCodeList,
direction: data.formData.direction,
}
const exportUrl = process.env.VUE_APP_API_BASE_URL + '/btyBank/export?' + Object.keys(params).map(key => `${key}=${params[key]}`).join('&')
setting.fetchDownload(exportUrl)
}
必须参数校验
/** 检查表单 */
const checkForm = () => {
let flag = true
if(data.formData.searchBeginTime == '') {
message.error('请选择开始日期')
flag = false
}
if(data.formData.searchEndTime == '') {
message.error('请选择结束日期')
flag = false
}
if(data.formData.orgCodeList.length == 0) {
message.error('请选择组织机构')
flag = false
}
return flag
}
方法注册
return {
...toRefs(data),
exportExcel,
}