vue 通過axios下載檔案
阿新 • • 發佈:2022-03-28
//準備工作 npm i axios npm install js-file-download --save //https://github.com/kennethjiang/js-file-download //vue2.x //main.js //新增到原型中 import axios from 'axios' Vue.prototype.$axios=axios //使用 import fileDownload from 'js-file-download'; download() { this.$axios.get('下載地址', { responseType: 'blob', }).then(res => { fileDownload(res.data, '下載的檔名字'); }); } //vue3.x //main.js //新增到原型中 import axios from "axios"; const app = createApp(App); app.config.globalProperties.$axios = axios; //使用 <script setup> import fileDownload from 'js-file-download'; import { getCurrentInstance } from "vue"; const { proxy } = getCurrentInstance();//獲取原型 const Axios = proxy.$axios;//Axios就是掛在的原型(相當於vue2中的this.$axios) const download =()=> { Axios.get('下載地址', { responseType: 'blob', }).then(res => { fileDownload(res.data, '下載的檔名字'); }); } </script>