关于防止多次请求的一些小操作

目的:在统一封装请求的时候处理,就不用每次请求去处理

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;
    },
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值