vue中实现点击下载
方案一:下载服务器上的静态文件(最简单)
如果要下载的是服务器上的静态资源(如 PDF、Excel、图片等),可以直接通过 <a> 标签实现,这是最简洁高效的方式。
<template>
<div>
<!-- 方式1:直接使用a标签 -->
<a
href="/static/files/文档.pdf"
download="自定义文件名.pdf"
class="download-btn"
>
点击下载文档
</a>
<!-- 方式2:按钮触发(更美观) -->
<button @click="downloadStaticFile">下载Excel文件</button>
</div>
</template>
<script>
export default {
methods: {
downloadStaticFile() {
// 创建a标签
const link = document.createElement('a');
// 设置文件地址(相对路径/绝对路径都可以)
link.href = '/static/files/数据表格.xlsx';
// 设置下载后的文件名(可选)
link.download = '2026年度数据.xlsx';
// 触发点击
link.click();
// 移除创建的标签
document.body.removeChild(link);
}
}
}
</script>
<style scoped>
.download-btn {
display: inline-block;
padding: 8px 16px;
background: #409eff;
color: white;
text-decoration: none;
border-radius: 4px;
margin-right: 10px;
}
button {
padding: 8px 16px;
background: #67c23a;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>方案二:下载接口返回的二进制文件(如后端生成的 Excel/PDF)
如果文件是后端接口动态生成的(比如根据查询条件生成 Excel),需要先请求接口获取二进制数据,再转换为下载链接。
<template>
<button @click="downloadDynamicFile">下载动态生成的报表</button>
</template>
<script>
// 假设你使用axios请求接口
import axios from 'axios';
export default {
methods: {
async downloadDynamicFile() {
try {
// 1. 请求接口,注意设置responseType为blob
const response = await axios({
url: '/api/report/export', // 后端接口地址
method: 'GET', // 根据后端要求选择GET/POST
params: { id: 123 }, // 接口参数
responseType: 'blob' // 关键:指定返回类型为二进制
});
// 2. 处理返回的二进制数据
const blob = new Blob([response.data], {
// 根据文件类型设置MIME类型
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
// 3. 创建下载链接并触发下载
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = '动态报表.xlsx'; // 自定义文件名
link.click();
// 4. 释放URL对象,避免内存泄漏
window.URL.revokeObjectURL(downloadUrl);
document.body.removeChild(link);
this.$message.success('下载成功'); // 可选:提示用户
} catch (error) {
console.error('下载失败:', error);
this.$message.error('下载失败,请重试');
}
}
}
}
</script>方案三:Vue3 + Composition API 版本
如果你使用的是 Vue3,这里是适配 Composition API 的写法:
<template>
<button @click="downloadFile">Vue3下载文件</button>
</template>
<script setup>
import { ElMessage } from 'element-plus'; // 以Element Plus为例
import axios from 'axios';
const downloadFile = async () => {
try {
const response = await axios({
url: '/api/file/download',
method: 'GET',
responseType: 'blob'
});
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'vue3下载文件.txt';
a.click();
window.URL.revokeObjectURL(url);
ElMessage.success('下载成功');
} catch (err) {
ElMessage.error('下载失败');
}
};
</script>






