方式一:a标签点击实现
<template> <div class=""> <el-button size="small" @click="downloadFile" >保存文件</el-button> </div> </template> <script> export default { methods: { downloadFile() { var blob = new Blob(['Hello, world!'], { type: 'text/plain;charset=utf-8', }); // 存在浏览器兼容性 let href = URL.createObjectURL(blob); let alink = document.createElement('a'); alink.style.display = 'none'; alink.download = '文件名.txt'; //下载后文件名 alink.href = href; document.body.appendChild(alink); alink.click(); document.body.removeChild(alink); //下载完成移除元素 URL.revokeObjectURL(href); //释放掉blob对象 }, }, }; </script> <style lang="scss" scoped> </style>
方式二:file-saver实现保存
文档:https://www.npmjs.com/package/file-saver
cdn: https://www.jsdelivr.com/package/npm/file-saver
依赖
npm i file-saver
语法
FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom } )
示例
<template> <div class=""> <el-button size="small" @click="saveFile" >保存文件</el-button> </div> </template> <script> /** * 文件保存 */ import FileSaver from 'file-saver'; export default { methods: { saveFile() { var blob = new Blob(['Hello, world!'], { type: 'text/plain;charset=utf-8', }); FileSaver.saveAs(blob, '文件名.txt'); }, }, }; </script> <style lang="scss" scoped> </style>