vue3 如何下载文件
时间: 2023-07-26 11:35:59 浏览: 37
在 Vue 3 中,可以使用浏览器原生的 `fetch()` 函数或者第三方库例如 Axios 来下载文件。
下面是一个使用 `fetch()` 函数下载文件的例子:
```vue
<template>
<div>
<button @click="downloadFile">Download File</button>
</div>
</template>
<script>
export default {
methods: {
downloadFile() {
const url = 'http://example.com/file.pdf';
fetch(url)
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
}
}
}
</script>
```
这段代码会通过 `fetch()` 函数获取指定 URL 的文件,并将其转换为一个二进制数据块。然后,它会创建一个 URL 对象,并将其赋值给一个新创建的 `a` 标签的 `href` 属性。最后,它会将这个标签添加到页面上,并调用 `click()` 方法来触发下载操作。
如果你使用的是 Axios,下载文件的过程会更简单一些。下面是一个使用 Axios 下载文件的例子:
```vue
<template>
<div>
<button @click="downloadFile">Download File</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
methods: {
downloadFile() {
const url = 'http://example.com/file.pdf';
axios({
url,
method: 'GET',
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
}
}
}
</script>
```
这段代码会使用 Axios 发送一个 GET 请求,并将响应的数据类型设置为 blob。然后,它会创建一个 URL 对象,并将其赋值给一个新创建的 `a` 标签的 `href` 属性。最后,它会将这个标签添加到页面上,并调用 `click()` 方法来触发下载操作。