当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue+axios实现文件下载及vue中使用axios的实例

vue+axios实现文件下载及vue中使用axios的实例

2019年06月02日  | 移动技术网IT编程  | 我要评论

天津中考录取分数线,嚣张宝贝黑道妈,铲车故意撞击轿车

功能:点击导出按钮,提交请求,下载excel文件;

第一步:跟后端童鞋确认交付的接口的response header设置了

response header

以及返回了文件流。

第二步:修改axios请求的responsetype为blob,以post请求为例:

axios({
  method: 'post',
  url: 'api/user/',
  data: {
    firstname: 'fred',
    lastname: 'flintstone'
  },
  responsetype: 'blob'
}).then(response => {
  this.download(response)
}).catch((error) => {

})

第三步:请求成功,拿到response后,调用download函数(创建a标签,设置download属性,插入到文档中并click)

methods: {
  // 下载文件
  download (data) {
    if (!data) {
      return
    }
    let url = window.url.createobjecturl(new blob([data]))
    let link = document.createelement('a')
    link.style.display = 'none'
    link.href = url
    link.setattribute('download', 'excel.xlsx')

    document.body.appendchild(link)
    link.click()
  }
}

下面在通过实例代码看下vue中使用axios

1.安装axios

npm:

$ npm install axios -s

cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2.配置axios

在项目中新建api/index.js文件,用以配置axios

api/index.js

import axios from 'axios';
let http = axios.create({
 baseurl: 'http://localhost:8080/',
 withcredentials: true,
 headers: {
  'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
 },
 transformrequest: [function (data) {
  let newdata = '';
  for (let k in data) {
   if (data.hasownproperty(k) === true) {
    newdata += encodeuricomponent(k) + '=' + encodeuricomponent(data[k]) + '&';
   }
  }
  return newdata;
 }]
});
function apiaxios(method, url, params, response) {
 http({
  method: method,
  url: url,
  data: method === 'post' || method === 'put' ? params : null,
  params: method === 'get' || method === 'delete' ? params : null,
 }).then(function (res) {
  response(res);
 }).catch(function (err) {
  response(err);
 })
}
export default {
 get: function (url, params, response) {
  return apiaxios('get', url, params, response)
 },
 post: function (url, params, response) {
  return apiaxios('post', url, params, response)
 },
 put: function (url, params, response) {
  return apiaxios('put', url, params, response)
 },
 delete: function (url, params, response) {
  return apiaxios('delete', url, params, response)
 }
}

这里的配置了post、get、put、delete方法。并且自动将json格式数据转为url拼接的方式

同时配置了跨域,不需要的话将withcredentials设置为false即可

并且设置了默认头部地址为:,这样调用的时候只需写访问方法即可

3.使用axios

注:put请求默认会发送两次请求,第一次预检请求不含参数,所以后端不能对put请求地址做参数限制

首先在main.js中引入方法

import api from './api/index.js';
vue.prototype.$api = api;

然后在需要的地方调用即可

this.$api.post('user/login.do(地址)', {
  "参数名": "参数值"
}, response => {
   if (response.status >= 200 && response.status < 300) {
    console.log(response.data);\\请求成功,response为成功信息参数
   } else {
    console.log(response.message);\\请求失败,response为失败信息
   }
});


总结

以上所述是小编给大家介绍的vue+axios实现文件下载及vue中使用axios的实例,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网