vue 实现下载文件功能
时间: 2023-09-07 09:11:12 浏览: 43
1. 在 Vue 组件中引入 axios 库
```javascript
import axios from 'axios'
```
2. 创建一个方法,用于发送请求并下载文件
```javascript
downloadFile() {
axios({
url: '下载文件的接口地址',
method: 'get',
responseType: 'blob' // 表示响应类型为二进制流
}).then(response => {
const fileName = '文件名.xxx' // 文件名
const content = response.data // 文件流
const blob = new Blob([content])
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = fileName
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
})
}
```
3. 在模板中添加一个按钮,绑定 downloadFile 方法
```html
<template>
<div>
<button @click="downloadFile">下载文件</button>
</div>
</template>
```