如果项目中有多个页面用到附件下载的方法,那么可以将这个方法封装成一个全局方法,减少重复代码。
在
main.js
同级目录下新建一个GLOBAL.vue文件,在里面可以声明很多全局共用方法。
>> GLOBAL.vue
<scirpt>
import { fileDownload } from '../HTTP/myApis'
const downloadAttachment = async (fileid, rename, type) => {
await fileDownload({id: fileid, type: type}).then(res => {
if(res.code == 0) {
instance.$message.error('附件下载出错:' + res.msg)
}else {
let extentionType = rename.substring(rename.lastIndexOf('.')).toLowerCase();
let fileType = ''
switch(extentionType) {
case '.doc':
fileType = 'application/msword'
break
case '.txt':
fileType = 'text/plain'
break
case '.docx':
fileType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
break
case '.xls':
fileType = 'application/vnd.ms-excel'
break
case '.xlsx':
fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
break
case '.jpg':
fileType = 'image/jpeg'
break
case '.png':
fileType = 'image/png'
break
case '.ppt':
fileType = 'application/vnd.ms-powerpoint'
break
case '.pdf':
fileType = 'application/pdf'
break
case '.zip':
fileType = 'application/zip'
break
default:
break
}
let blob = new Blob([res], {type: fileType});
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = rename
link.click();
}
})
}
export default ({
downloadAttachment
})
</scirpt>
使用方法:
>> main.js
import global_ from './Global.vue'
Vue.prototype.GLOBAL = global_
>> xx.vue
this.GLOBAL.downloadAttachment(a, b, c);