vuex中代码
import Vue from 'vue'
import Vuex from 'vuex'
import { Loading } from 'element-ui'
Vue.use(Vuex)
Vue.use(Loading)
export default new Vuex.Store({
state: {
// 请求计数
apiCount: 0,
// loading实例
loadingInstance: null
},
mutations: {
/* 打开Loading */
startLoading(state, msg) {
state.loadingInstance = Loading.service({
lock: true,
text: msg || '加载中...',
background: 'rgba(0, 0, 0, 0.7)'
})
},
/* 关闭loading */
closeLoading(state) {
state.loadingInstance.close()
},
/* 更新请求线程池 */
updateApiCount(state, handle) {
if (handle === 'add') {
state.apiCount++
this.commit('startLoading')
} else {
state.apiCount--
if (state.apiCount <= 0) {
this.commit('closeLoading')
}
}
}
},
actions: {},
modules: {
}
})
封装请求
import axios from 'axios'
import qs from 'qs'
import store from '@store/index'
// create an axios instance
const service = axios.create({
// api 的 base_url
baseURL: process.env.VUE_APP_API,
timeout: 2 * 30 * 60 * 1000, // 请求超时时间
transformRequest: [function(data) {
return qs.stringify(data)
}]
})
service.interceptors.request.use(
config => {
store.commit('updateApiCount', 'add')
return config
},
error => {
store.commit('updateApiCount', 'sub')
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
store.commit('updateApiCount', 'sub')
const res = response.data
// todo
return res
},
error => {
store.commit('updateApiCount', 'sub')
console.log('请求err' + error) // for debug
// Message({
// // message: error.message,
// message: '联网异常,请检查网络状态',
// type: 'error',
// duration: 2 * 1000
// })
return Promise.reject(error)
}
)
export default service