vue 通过axios下载文件

//准备工作
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>
    
		
    

  

posted @ 2022-03-28 09:49  小万子呀  阅读(1373)  评论(0编辑  收藏  举报