① 在lab文件夹下新建一个axios.js的文件
import axios from 'axios'
import { baseURL } from '@/config'
class HttpRequest {
constructor (baseUrl = baseURL) {
this.baseUrl = baseUrl
this.queue = {}
}
getInsideConfig () {
const config = {
baseURL: this.baseUrl,
headers: {
//
}
}
return config
}
distroy (url) {
delete this.queue[url]
if (!Object.keys(this.queue).length) {
// Spin.hide()
}
}
interceptors (instance, url) {
instance.interceptors.request.use(config => {
// 添加全局的loading...
if (!Object.keys(this.queue).length) {
// Spin.show()
}
this.queue[url] = true
return config
}, error => {
return Promise.reject(error)
})
instance.interceptors.response.use(res => {
this.distroy(url)
const { data } = res
return data
}, error => {
this.distroy(url)
return Promise.reject(error.response.data)
})
}
request (options) {
const instance = axios.create()
options = Object.assign(this.getInsideConfig(), options)
this.interceptors(instance, options.url)
return instance(options)
}
}
export default HttpRequest
② config文件夹下的index.js
export const baseURL = process.env.NODE_ENV === 'production'
? '/api/'
: ''
③ 使用:api文件夹下的index.js
import HttpRequest from '@/lab/axios'
const axios = new HttpRequest()
export default axios
api文件夹下的user.js
import axios from './index'
export const getUserInfo = ({ userId }) => {
return axios.request({
url: '/getUserInfo',
method: 'post',
data: {
userId
}
})
}
组件里面就能使用
import {getUserInfo} from '@/api/user'
getInfo () {
getUserInfo({ userId: 21 }).then(res => {
console.log('res: ', res.data)
})
},