vue的axios数据请求以及接口封装

第一步:


'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_HOST: '"/apis"'
})

第二步:

'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_HOST: '""',
}

接口封装对象:

const root = process.env.API_HOST

export default {
  system: { // 系统管理
    getUser: root + '/system/user/getUserData'
    }
}

main.js引入 

import urls from '@/request/api'
Vue.prototype.$urls = urls;

axios请求封装:

import axios from 'axios'
import QS from 'qs'

const get = function (url, params, loadingShow=true) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params }, {loading: loadingShow})
      .then(res => {
        resolve(res.data);
      }).catch(err => {
        reject(err.data)
      })
  });
}


// TODO: loadingShow = 是否开起全屏loading
const post = function (url, params, loadingShow=true) {
  return new Promise((resolve, reject) => {
    axios.post(url, QS.stringify(params), {loading: loadingShow})
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  });
}

const del = function (url, params) {
  return new Promise((resolve, reject) => {
    axios.delete(url + '/' + params.id, {})
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  });
}

const put = function (url, data) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  });
}

const bodypost = function (url, params, loadingShow=true) {
  return new Promise((resolve, reject) => {
    axios.post(url, params, {loading: loadingShow})
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  });
}

const getExport = function (url, params, fileName = '导出数据文件.xlsx', method = 'post') {
  return new Promise((resolve, reject) => {
    this.$axios({
      url,
      method,
      params,
      responseType: "blob"
    }).then(res => {
      const content = res.data;
      //构造一个blob对象来处理数据
      const blob = new Blob([content], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
      });
      //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
      //IE10以上支持blob但是依然不支持download
      if ("download" in document.createElement("a")) {
        //支持a标签download的浏览器
        const link = document.createElement("a"); //创建a标签
        link.download = fileName; //a标签添加属性
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click(); //执行下载
        URL.revokeObjectURL(link.href); //释放url
        document.body.removeChild(link); //释放标签
      } else {
        //其他浏览器
        navigator.msSaveBlob(blob, fileName);
      }
    });
  });
}

export default {
  get,
  post,
  del,
  put,
  bodypost,
  getExport
}

 main.js引入

import axiosHttp from '@/request/http'

Vue.prototype.$post = axiosHttp.post;

Vue.prototype.$get = axiosHttp.get;

Vue.prototype.$del = axiosHttp.del;

Vue.prototype.$put = axiosHttp.put;

页面使用

 handleQueryCondition() {
      // 查询条件
      let obj = {
        deptName:
          this.search.deptName == "" || this.search.deptName == null
            ? undefined
            : this.search.deptName,
        plate:
          this.search.plate == "" || this.search.plate == null
            ? undefined
            : this.search.plate,
        beginDate:
          this.search.selectTime == "" || this.search.selectTime == null
            ? undefined
            : this.search.selectTime[0],
        endDate:
          this.search.selectTime == "" || this.search.selectTime == null
            ? undefined
            : this.search.selectTime[1],
        page: this.currentPage,
        size: this.pageSize,
      };
      return obj;
    },

    handleDataValidation(data) {
      // 数据验证
      return data == undefined || data == null ? "" : data;
    },

    async handleTableList() {
      // 表格数据
      let url = this.$urls.attendance.vehicleMonth.queryData;
      let obj = this.handleQueryCondition();
      let res = await this.$post(url, obj);
      this.tableList = [];
      if (res.errorCode == "0" && res.data.list.length > 0) {
        for (let i = 0; i < res.data.list.length; i++) {
          this.tableList.push({
            deptName: this.handleDataValidation(res.data.list[i].deptName),
            driverName: this.handleDataValidation(res.data.list[i].driverName),
            plate: this.handleDataValidation(res.data.list[i].plate),
            icCard: this.handleDataValidation(res.data.list[i].cardId),
            attTotal: this.handleDataValidation(res.data.list[i].attTotal),
            beAtt: this.handleDataValidation(res.data.list[i].beAtt),
            classTotal: this.handleDataValidation(res.data.list[i].classTotal),
            beClass: this.handleDataValidation(res.data.list[i].beClass),
            late: this.handleDataValidation(res.data.list[i].late),
            early: this.handleDataValidation(res.data.list[i].early),
            absence: this.handleDataValidation(res.data.list[i].absence),
            rest: this.handleDataValidation(res.data.list[i].rest),
          });
        }
        this.pagepaging = res.data.total;
      }
    },

vue请求代理

 


module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/apis': {
        target: 'https://192.168.0.12', // 正式环境
        changeOrigin: true, //是否跨域
        pathRewrite: {
          '^/apis': '' //重写接口
        }
      }
    },

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值