vue 项目 api 统一管理

37 篇文章 0 订阅
17 篇文章 0 订阅

因为项目迁移所以进行api统一管理

api 文件夹下

index.js

import request from '@/lib/request.js'
import product from './product.js'

function ajax (params, options = {}) {
  if (params) {
    if (options.method === 'post') {
      if (options.isConcat) {
        options = concatParams(options, params)
      } else {
        options.data = params
      }
    } else {
      options.params = params
    }
  }
  return request(options)
}

function concatParams (options, params) {
  let concatUrl = ''
  for (let i in params) {
    concatUrl = concatUrl + `&${i}=${params[i]}`
  }
  if (options.url.indexOf('?') > -1) {
    options.url = `${options.url}${concatUrl}`
  } else {
    options.url = `${options.url}?${concatUrl.substring(1)}`
  }
  return options
}

const apiAll = {
  ...product
}
let apis = {}
for (let i in apiAll) {
  apis[i] = function (params) {
    return ajax.bind(this, params, apiAll[i])()
  }
}
export default apis

其他 api

export default {
  disAndEier: {
    url: `/tp/supr/dis`,
    method: 'post',
    isConcat: true
  }
}

axios 请求

import axios from './axios'

const ajax = axios.create({
  timeout: 5000 // 请求超时时间
})

/**
 * 实例配置
 */
// request拦截器
ajax.interceptors.request.use(config => {
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
ajax.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    return Promise.reject(error)
  }
)

export default ajax

main.js

import api from '@/api'

Vue.prototype.$api = api

具体使用

 await this.$api.disAndEier({id: 1}) 配合async使用

all 的实现

        let [ret1, ret2] = await Promise.all([
          this.$api.queryCate(),
          this.$api.queryAllProvinces({})
        ])
        console.log(ret1, ret2)

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值