下载模板 ,通用下载方法this.download

349 阅读1分钟

下载方法的封装

  • 这个项目是封装在src/utils/request.js里面的
// 通用下载方法
export function download(url, params, filename) {
    downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
    return service.post(url, params, {
        transformRequest: [(params) => { return tansParams(params) }],
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        responseType: 'blob'
    }).then(async(data) => {
        const isLogin = await blobValidate(data);
        if (isLogin) {
            const blob = new Blob([data])
            saveAs(blob, filename)
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
            Message.error(errMsg);
        }
        downloadLoadingInstance.close();
    }).catch((r) => {
        console.error(r)
        Message.error('下载文件出现错误,请联系管理员!')
        downloadLoadingInstance.close();
    })
}

全局注册

  • 为了方便后续引用,需要全局注册一下;
import {download} from "@/utils/request";//全局引入

Vue.prototype.download = download //全局注册

页面使用

  • 在自己需要的页面中引用下载方法;
//下载
down(){
this.download(
'/download,' //这是下载路径,后端给的接口
{},//下载时传入的参数,如果不需要传参,直接为空;
`下载名称_template_$(new Date().getTime()}.xlsx)`
//下载的文件名和后缀名
)

}