封装成组件,多了一个element按钮的对象属性,bottonObj集成element原生属性,参考自定义样式。
文件下载参数 fileName(必传,看和后端约定,可以在response的header中返回文件名称)、params(请求参数非必传)、requestType(请求类型非必传,默认get)
*另外请求地址采用获取配置文件的方式,token直接获取localStorage。可以根据实际项目约定修改。
1、组件源码 main.vue
<template>
<div>
<el-button :size="bottonObj.size"
:type="bottonObj.type"
:plain="bottonObj.plain"
:round="bottonObj.round"
:circle="bottonObj.circle"
:loading="loading"
:disabled="bottonObj.disabled"
:icon="bottonObj.icon"
@click="download">{{bottonObj.text || '下载'}}</el-button>
</div>
</template>
<script>
import main from './main.js';
export default {
name: 'z-download',
props: {
bottonObj: {
type: Object,
default: () => {
return {}
}
},
fileName: {
type: String,
required: true
},
params: {
type: Object,
default: () => {
return {}
}
},
requestType: {
type: String,
}
},
data() {
return {
loading: false,
}
},
methods: {
async download() {
this.loading = true;
let res = await main(this.fileName, this.params, this.requestType);
if (res) {
this.loading = false;
}
}
}
}
</script>
2、main.js
/**
* @createDate 2022年11月10日
* @name 导出文件名称
* @params 请求参数
* @type 请求类型
*/
export default (fileName, params = '', type = 'GET') => {
return new Promise((resolve, reject) => {
const url = process.env.VUE_APP_BASE_DOWNLOAD_URL
type = type.toUpperCase();
let xhr = new XMLHttpRequest();
if (type === 'POST') {
let data = params ? JSON.stringify(params) : {};
xhr.open('POST', url, true);
xhr.responseType = 'blob';
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));
xhr.send(data);
xhr.onload = function() {
if (this.status === 200) {
let blob = this.response;
let a = document.createElement('a');
let aUrl = window.URL.createObjectURL(blob);
a.href = aUrl;
a.download = fileName;
a.click();
a.remove()
}
};
resolve(xhr)
} else {
let newUrl = url;
if (params) {
let getParams = '?';
for (let key in params) {
if (params[key]) {
getParams += `${key}=${params[key]}&`
}
}
newUrl + url + getParams
}
xhr.open('GET', newUrl, true);
xhr.responseType = 'blob';
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));
xhr.send();
xhr.onload = function() {
if (this.status === 200) {
let blob = this.response;
let a = document.createElement('a');
let aUrl = window.URL.createObjectURL(blob);
a.href = aUrl;
a.download = fileName;
a.click();
a.remove();
}
};
resolve(xhr)
}
})
};
3、测试使用 testDownload.vue,当挂载全局,或者打包上传npm之后,只需要
<download fileName="测试文件.xlsx" />
这样一行几个字代码就能实现文件下载,岂不是美滋滋
<template>
<download fileName="测试文件.xlsx" />
</template>
<script>
import download from '../../../packages/z-download/src/main.vue'
export default {
components: {
download
},
}
</script>
4、效果预览