因为项目迁移所以进行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)