Chinaunix首页 | 论坛 | 博客
  • 博客访问: 285035
  • 博文数量: 93
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 830
  • 用 户 组: 普通用户
  • 注册时间: 2016-02-25 10:44
个人简介

一杯茶,一台电脑

文章分类

全部博文(93)

文章存档

2018年(4)

2017年(57)

2016年(32)

分类: JavaScript

2018-03-22 16:10:31


  1. // 配置API接口地址
  2. // var root = ''
  3. var root = '/api/'
  4. // 引用axios
  5. var axios = require('axios')
  6. // 自定义判断元素类型JS
  7. function toType (obj) {
  8.   return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
  9. }
  10. // 参数过滤函数
  11. function filterNull (o) {
  12.   for (var key in o) {
  13.     if (o[key] === null) {
  14.       delete o[key]
  15.     }
  16.     if (toType(o[key]) === 'string') {
  17.       o[key] = o[key].trim()
  18.     } else if (toType(o[key]) === 'object') {
  19.       o[key] = filterNull(o[key])
  20.     } else if (toType(o[key]) === 'array') {
  21.       o[key] = filterNull(o[key])
  22.     }
  23.   }
  24.   return o
  25. }
  26. /*
  27.   接口处理函数
  28.   这个函数每个项目都是不一样的,我现在调整的是适用于
  29.    的接口,如果是其他接口
  30.   需要根据接口的参数进行调整。参考说明文档地址:
  31.   
  32.   主要是,不同的接口的成功标识和失败提示是不一致的。
  33.   另外,不同的项目的处理方法也是不一致的,这里出错就是简单的alert
  34. */

  35. function apiAxios (method, url, params, success, failure) {
  36.   if (params) {
  37.     params = filterNull(params)
  38.   }
  39.   axios({
  40.     method: method,
  41.     url: url,
  42.     data: method === 'POST' || method === 'PUT' ? params : null,
  43.     params: method === 'GET' || method === 'DELETE' ? params : null,
  44.     baseURL: root,
  45.     withCredentials: false
  46.   })
  47.     .then(function (res) {
  48.       if (res.data.success === true) {
  49.         if (success) {
  50.           success(res.data)
  51.         }
  52.       } else {
  53.         if (failure) {
  54.           failure(res.data)
  55.         } else {
  56.           window.alert('error: ' + JSON.stringify(res.data))
  57.         }
  58.       }
  59.     })
  60.     .catch(function (err) {
  61.       let res = err.response
  62.       if (err) {
  63.         window.alert('api error, HTTP CODE: ' + res.status)
  64.       }
  65.     })
  66. }

  67. // 返回在vue模板中的调用接口
  68. export default {
  69.   get: function (url, params, success, failure) {
  70.     return apiAxios('GET', url, params, success, failure)
  71.   },
  72.   post: function (url, params, success, failure) {
  73.     return apiAxios('POST', url, params, success, failure)
  74.   },
  75.   put: function (url, params, success, failure) {
  76.     return apiAxios('PUT', url, params, success, failure)
  77.   },
  78.   delete: function (url, params, success, failure) {
  79.     return apiAxios('DELETE', url, params, success, failure)
  80.   }
  81. }
main.js 代码如下:
import api from './api/index.js'
Vue.prototype.$api = api

阅读(536) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~