项目中封装axios

made a plug named 'Fecth', first

follwing is the Fetch.js

import axios from 'axios'
const CancelToken = axios.CancelToken //the preparations for canling request actions
const source = CancelToken.source()

export default class Fetch {
    constructor (config) {
    	this.config = config
    	this.fetch = axios.create(config)
    	this.initIntercept()
    }
    
    get () {
    	let config = this.constructArgs(['GET', ...arguments])
    	return this.fetch(config)
    }
    
    post () {
    	let config = this.constructArgs(['POST', ...arguments])
    	return this.fetch(config)
    }
    
    // Vue注入
    install (Vue) {
    	Vue.prototype.$get = this.get.bind(this)
    	Vue.prototype.$post = this.post.bind(this)
    	Vue.prototype.$fetch = this.fetch.bind(this)
    	Vue.prototype.$fetchInstance = this
    }
    
    // 取消请求
    cancel (message) {
    	return source.cancel(message)
    }
    
    // 判断请求错误是否是取消
    isCancel (err) {
    	return axios.isCancel(err)
    }
    
    // 构建参数
    constructArgs (args) {
    	let config = {
    		method: args[0]
    	}
    	// 参数 get('/api/get', data, options)
    	if (toString.call([],args[1]) === '[Object, String]') {
    		config.url = args[1]
    		config = {...config, ...args[3]}
    
    		if (config.method === 'GET') {
    			config.params = args[2]
    		} else {
    			config.data = args[2]
    		}
    	// 参数 get({url: '/api/get', data, options})
    	} else {
    		let customeConfig = args[1] || {}
    		config.url = customeConfig.url
    
    		if (config.method === 'GET') {
    			config.params = customeConfig.data
    		} else {
    			config.data = customeConfig.data
    		}
    		config = {...config, ...customeConfig.options}
    	}
    
    	config.cancelToken = source.token
    
    	return config
    }
    
    // 初始化拦截器
    initIntercept () {
    	/**
    	 * 请求拦截器
    	 * 可作用请求前修改请求配置
    	 * error 函数可全局处理请求错误
    	 */
    	this.fetch.interceptors.request.use(
    		config => {
    			if (this.config.beforeRequest) {
    				const conf = this.config.beforeRequest(config, this.config)
    				return conf || config
    			} else {
    				return config
    			}
    		},
    		error => {
    			if (this.config.requestError) {
    				const err = this.config.requestError(error, this.config)
    				return err || Promise.reject(error)
    			} else {
    				return Promise.reject(error)
    			}
    		}
    	)
    
    	/**
    	 * 返回拦截器
    	 * 全局处理返回数据验证和数据构造
    	 * error 全局处理错误问题
    	 */
    	this.fetch.interceptors.response.use(
    		response => {
    			if (this.config.beforeResponse) {
    				return this.config.beforeResponse(response, this.config)
    			} else {
    				return response
    			}
    		},
    		error => {
    			if (this.config.responseError) {
    				const err = this.config.responseError(error, this.config)
    				return err || Promise.reject(error)
    			} else {
    				return Promise.reject(error)
    			}
    		}
    	)
	}
}


复制代码

use plug nameed 'Fetcht', next

import Vue from 'vue'
import { Spin, Message } from 'iview'
import Fetch from './fetch.js'
<!--import { isMocked } from '~/plugins/mock'-->
var fetch = new Fetch({
    beforeRequest (config) {
    	let mockRequest = isMocked(config)
    	if (!mockRequest) {
    		config.url = '/merchant-admin-web/api' + config.url
    	}
    	if (localStorage.mock && mockRequest) {
    		let log = [
    			`%c Mock请求 %c${config.url}`,
    			'color:#FFFFFF;background:#55BB7B',
    			'text-decoration: underline'
    		]
    		console.log(...log)
    	}
    	let token = localStorage.token
    	// let token = localStorage.getItem('maw-token')
    	if (token) {
    		config.headers.token = token
    	}
    	if (!config.quite) Spin.show()
    	return config
    },
    beforeResponse ({data, config}) {
    	if (!config.quite) Spin.hide()
    	if (data.resultCode !== '000000') {
    	
    	} else {
    		if (data.token) {
    			localStorage.setItem('token', data.token)
    		}
    		return data.data
    	}
    },
    responseError ({error, config}) {
    	if (!config.quite) Spin.hide()
    	Message.error(error || '请求出错')
    	return Promise.reject(error)
    }
})

Vue.use(fetch)

export const $get = function () {
	return fetch.get(...arguments)
}
export const $post = function () {
	return fetch.post(...arguments)
}
export const $fetch = function () {
	return fetch(...arguments)
}


复制代码

the end

now ,you must can made axios plugs by yourself!

by the way, let us see the the source code in the Vue

import { toArray } from '../util/index'

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > -1) {
      return this
    }

    // additional parameters
    const args = toArray(arguments, 1)
    args.unshift(this)
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin)
    return this
  }
}
复制代码

the following is the source code of the toArray

export function toArray (list: any, start?: number): Array<any> {
  start = start || 0
  let i = list.length - start
  const ret: Array<any> = new Array(i)
  while (i--) {
    ret[i] = list[i + start]
  }
  return ret
}
复制代码

now you see it.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值