Vue封装axios引入全局变量

2020-05-02  本文已影响0人  上海老宅男

我封装的比较low直接把所有方法暴露在外面
也有更好的封装方法

import axios from 'axios'
export default {
    apiGet(url, params) {
      var that=this
      return new Promise((resolve, reject) => {
        axios.get(url, {params}).then((response) => {
          resolve(response)
        }, (response) => {
          reject(response)
          _g.closeGlobalLoading()
          that.$message({
            message: '请求超时,请检查网络',
            type: 'warning'
          })
        }).catch(error => {
          console.log('shibai ',error)
        })
      })
    },
    apiPost(url, data) {
      var that = this
      // headers: {'Authorization': token }
      return new Promise((resolve, reject) => {
        axios.post(url, data,).then((response) => {
          resolve(response.data)
        }).catch((response) => {
          console.log('f', response)
          resolve(response)
          that.$message({
            message: '请求超时,请检查网络',
            type: 'warning'
          })
        })
      })
    },
    apiDownload(url,param){
      return new Promise((resolve, reject) => {
        axios.post(url, param, {

          'responseType': 'blob'  //设置响应的数据类型为一个包含二进制数据的 Blob 对象,必须设置!!!
        }).then(function (response) {
          const blob = new Blob([response.data]);
          const fileName = Math.floor(Math.random()*1000000000)+'.xlsx';
          const linkNode = document.createElement('a');

          linkNode.download = fileName; //a标签的download属性规定下载文件的名称
          linkNode.style.display = 'none';
          linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
          document.body.appendChild(linkNode);
          linkNode.click();  //模拟在按钮上的一次鼠标单击

          URL.revokeObjectURL(linkNode.href); // 释放URL 对象
          document.body.removeChild(linkNode);
          resolve(response.data)
        }).catch(function (error) {
          console.log(error);
          resolve(error)
        });
      });


    },
    apiDelete(url, id) {
      return new Promise((resolve, reject) => {
        axios.delete(url + id).then((response) => {
          resolve(response.data)
        }, (response) => {
          reject(response)
          _g.closeGlobalLoading()
          bus.$message({
            message: '请求超时,请检查网络',
            type: 'warning'
          })
        })
      })
    },
    apiPut(url, id, obj) {
      return new Promise((resolve, reject) => {
        axios.put(url + id, obj).then((response) => {
          resolve(response.data)
        }, (response) => {
          _g.closeGlobalLoading()
          bus.$message({
            message: '请求超时,请检查网络',
            type: 'warning'
          })
          reject(response)
        })
      })
    }
  }

在main.js里面引入

import http from './api/http'
Vue.prototype.http = http

就可以愉快的在页面里面调用了

this.http.apiGet('xxx地址', params).then(res => {
                //请求成功
            }).catch(error => {
              //请求失败
            })
上一篇下一篇

猜你喜欢

热点阅读