vue axios封装,请求拦截配置,api管理

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) {
			......
		}
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值