🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# axios ## **axios请求封装** ```javascript import Vue from 'vue' export function getEdwAction (url, params, commit, mutation = '', timeout = 0, retry = 1) { url = process.env.EDW_API_PATH + url // 兼容IE--get请求有缓存 if (window.ActiveXObject || 'ActiveXObject' in window) { let isHaveParams = url.match(/\?/) if (isHaveParams) { url = `${url}&${new Date().getTime()}` } else { url = `${url}?${new Date().getTime()}` } } return Vue.axios .get(url, { timeout, retry, params }) .then(response => { if (response.success) { if (mutation !== '') { commit(mutation, response.data) } return Promise.resolve(response.data) } const error = { errorMessage: response?.errorMessage ? response.errorMessage : '查询失败!' } return Promise.reject(error) }).catch(error => { if (mutation !== '') { commit(mutation, {}) } return Promise.reject(error) }) } // store--XXX.js--action使用 import api from '@/api/logManage' import httpUtil from '@/assets/js/httpUtil' const actions = { logGroupList ({ commit }, params) { return httpUtil.getAction(`${api.logGrouplist}?` + Util.jsonToString(params), commit, mutation.LOG_GROUP_LIST_REQUEST) } } ``` ## 取消上一个路由的请求 ```javascript import axios from 'axios'; import store from '@/store'; axios.interceptors.request.use(config => { if (config.url.indexOf('export.asyn.performance') === -1) { config.cancelToken = new axios.CancelToken(cancelReq => { store.commit('loading/pushReqPending', { reqPendingFun: cancelReq }); }); }, error => { return Promise.reject(error); } }) axios.interceptors.response.use( config => {}, error => { if (axios.isCancel(error)) { return new Promise(() => {}) } } }) // store/module/loading.js mutations: { pushReqPending (state, payload) { state.ReqPendingArr.push(payload.reqPendingFun) }, clearReqPending ({ ReqPendingArr }) { if (ReqPendingArr.length) { ReqPendingArr.forEach(item => { item('路由跳转取消上一个路由的请求') }) ReqPendingArr = [] } } } // 路由导航守卫 router.beforeEach(async (to, from, next) => { store.commit('loading/clearReqPending') }) ``` ## axios超时重连 ```javascript axios.interceptors.response.use(response => {}, error => { const retry = config ? config.retry : '' if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1 && retry) { config.__retryCount = config.__retryCount || 0 if (config.__retryCount >= config.retry) { Object.assign(error, { errorMessage: '请求超时' }) return Promise.reject(error) } config.__retryCount += 1 const backoff = new Promise((resolve) => { setTimeout(() => { resolve() }, config.retryDelay || 1) }) return backoff.then(() => axios(config)) } }) ``` ## dispatchAction ```javascript // commonMixin.js import Vue from 'vue' Vue.mixin({ methods: { dispatchAction(action, params = {}, plain = false) { return new Promise((resolve, reject) => { this.$store.dispatch(action, plain ? params : Object.assign({}, params)).then(resp => { resolve(resp) }).catch(error => { reject(error) }) }) } } }) // .vue文件使用 this.dispatchAction('getAlarmList', params).then(res => {}).catch(error => {}) // mapActions 区别 ...mapActions({ add: 'increment' // 映射 this.add() to this.$store.dispatch('increment') }) ``` ## url参数整合 ```javascript export function jsonToString (data) { let str = [] for (let p in data) { if (data.hasOwnProperty(p)) { // 把字符串作为 URI 组件进行编码 str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p])) } } return str.join('&') } // 使用 paramsSerializer序列化 // qs.stringify()作用是将对象或者数组序列化成URL的格式 const service = axios.create({ baseURL: '', withCredentials: true, // send cookies when cross-domain requests paramsSerializer: params => { return qs.stringify(params, { skipNulls: true, arrayFormat: 'repeat' }); }, timeout: 60000 }); ```