vue中axios封装
因为每个人在项目中封装的想法不同,所以这里只谈一般的封装思路
1.在src下创建一个文件夹request
interceptors文件夹,里面加个index.js:封装自己需要的请求拦截器,这里只写一个例子
// 加载提示
export function loading (request) {
let loadingInstance = null
request.interceptors.request.use(config => {
loadingInstance = UxLoading()
return config
})
request.interceptors.response.use(
response => {
loadingInstance.close()
return response
},
error => {
loadingInstance.close()
throw error
}
)
}
config.js:配置基本的请求设置
export const baseOpt = {
baseURL: '/api'
timeOut: 5000,
withCredentials: true,
headers: { 'X-Requested-With': 'XMLHttpRequest' }
}
// 这里时全局的拦截器,看自己需要设置,
// baseInterceptors 中的值是interceptors暴露出来的拦截器名
export const baseInter = [
'loading'
]
index.js:暴露封装好的request
import createRequest from './request'
import * as config from './config'
const request = (options, settings = { interceptors: [] }) => {
// 配置合并,默认拦截器和参数中的拦截器合并
const reqOptions = Object.assign({}, config.baseOpt , options)
const { interceptors, unMergeInter } = settings
// 拦截器选用
if (!Array.isArray(interceptors)) {
throw new Error('settings interceptors must be array')
}
// unMergeInter表示是否需要添加默认的拦截器
const interList = unMergeInter ? interceptors : config.baseInter .concat(interceptors)
return createRequest(reqOptions , interList )
}
export default request
request.js:给请求添加拦截器
import axios from 'axios'
import * as interMap from './interceptors'
export default function (options, interList) {
const request = axios.create()
// 挂载拦截器
interList.map(inter => {
if (!interMap [inter]) {
throw new Error(`interceptor ${inter} not found`)
}
return interMap [inter] // 在'./interceptors'中匹配对应的拦截器
}).map(inter => {
inter(request) // 给请求挂载拦截器
})
return request(options)
}
2.在src下创建一个文件夹api,集中管理api
modeles文件夹下一般是一个页面一个js文件,
js文件命名,例:menu.api.js 其中的api要与下面的index.js中的判断一致
import request from '@/request'
const Url = ''
export default {
name: 'Menu',
getData (params) {
return request({
url: `${Url }/getInfo/${params}`,
method: 'get',
})
}
}
index则是整合所有api
// 这里就职查找所有后缀为api.js的,也可按自己喜好修改
const apis = require.context('./modules', true, /\.api.js/)
const api = {}
apis.keys().map(key => {
const config = apis(key).default || { name: 'test' }
api[config.name] = config
})
export default api
3.在.vue文件中使用,此处省略在main.js中的挂载内容
methods: {
async init () {
// Menu是在api文件夹下modules内js文件的name属性,可查看上面的menu.js
const res = await this.$api.Menu.getData('good')
if (res.code) {
......
}
}
}