由于uview2.0取消了等待时间后出现等待框
使用vuex实现
//store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
timer: null
},
mutations: {
// 设置定时器
setTimer(state) {
uni.hideLoading()
clearTimeout(state.timer)
state.timer = null
state.timer = setTimeout(() => {
uni.showLoading({
title: "加载中...",
mask: false
})
state.timer = null;
}, 800);
},
clearTimer(state) {
uni.hideLoading()
clearTimeout(state.timer)
state.timer = null
},
},
// 异步操作
actions: {},
getters: {}
})
export default store
//main.js
import store from './store'
//把vuex定义成全局组件
Vue.prototype.$store = store
// 引入请求封装,将app参数传递到配置中
require('./config/request.js')(app)
app.$mount()
// config/request.js
import store from '../store'
module.exports = (vm) => {
// 初始化请求配置
uni.$u.http.setConfig((config) => {
/* config 为默认全局配置*/
config.baseURL = ''; /* 根域名 */
return config
})
// 请求拦截
uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
//设置定时器
store.commit('setTimer')
config.data = config.data || {}
config.header['Content-Type'] = config.method==="GET"? 'application/x-www-form-urlencoded':"application/json;charset=UTF-8"
if(getToken()) {
config.header['authorization'] = getToken()
}
return config
}, config => {
return Promise.reject(config)
})
// 响应拦截
uni.$u.http.interceptors.response.use((response) => {
//清除定时器
store.commit('clearTimer')
let {
data
} = response
if (data.code != 200 && data.code !==401) {
// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
if (data.msg) {
uni.$u.toast(data.msg)
}
}
return data === undefined ? {} : data
}, (response) => {
return Promise.reject(response)
})
}