目的:在统一封装请求的时候处理,就不用每次请求去处理
1.常见的就是防抖函数的使用
2.利用样式透明遮罩层盖住不能再次点击,例如axios:在请求前拦截前插入body全屏Div,请求结束无论成功还是失败都把Div移除(这里也可以用hide()或show())
3.今天做uniapp小程序的时候,不能操作Dom,又想只在发请求的时候改变是否需要遮罩的状态,利用vuex存贮更改的是否需要隐藏或者显示遮罩层,在页面取值,在统一封装请求的地方,通过store.commit(‘overlayshowchange’,false)改变vuex的值
import store from '../store/index.js'
const https = {
request(options = {}) {
const {
url,
method,
data,
loadhide
} = options;
let header = Object.assign({
'token': wx.getStorageSync('token')
}, {
'openId': wx.getStorageSync('openId')
}, {
'content-type': 'application/json' // 默认值
})
// 加载动画
if (!loadhide) {
wx.showLoading({
title: '加载中...'
});
store.commit('overlayshowchange',true)
}
return new Promise((resolve, reject) => {
wx.request({
url,
method,
data,
header,
success: function(res) {
wx.hideLoading();
store.commit('overlayshowchange',false)
// 判断网络
if (res.statusCode == 404) {
reject();
return false;
} else if (res.statusCode != 200) {
wx.showToast({
title: '网络出错,稍后在试!' + url,
icon: 'none'
});
return false;
}
// 成功返回数据
resolve(res.data);
},
fail: function(error) {
// 失败
wx.hideLoading();
store.commit('overlayshowchange',false)
wx.showToast({
title: '网络出错,稍后在试!',
icon: 'none'
});
reject(error);
},
complete: function() {
wx.hideLoading();
store.commit('overlayshowchange',false)
}
});
});
}
};
export default https;
在需要使用的页面
import {
mapState,
mapMutations
} from 'vuex';
computed: {
...mapState(['overlayshow'])
},
通过this.overlayshow就可以取到
4.说到vuex想到昨天做项目的时候,因为这是状态存贮,刷新页面就没有了,所以我们需要和localStorege结合使用,
大概就是
在mutation的时候
mutations: {
SET_MENULIST: (state, menuList) => {
LocalSorage.set('menuList', menuList);//先存本地
// localStorage.setItem('menuList', JSON.stringify(menuList));
state.menuList = menuList;
},
取得时候
const getters = {
menuList: state => {
if (!state.menu.menuList) {
state.menu.menuList = LocalSorage.get('menuList');
}
return state.menu.menuList;
},
}