常用的utils工具函数

深拷贝对象或数组

	deepClone(source){
		// 排除null 和不是对象或数组的值
		if(source === null || typeof source !== 'object'){
			return source
		}
		let isArray = Array.isArray(source)
		let result = isArray ? []:{}
		if(isArray){
			result = source.map(item =>{
				return (item && typeof item === 'object') ? deepClone(item) : item
			})
		}else {
			const keys = Object.keys(source)
			keys.forEach(key =>{
				let val = source[key]
				result[key] = val && typeof val === 'object' ? deepClone(val) : val
			})
		}
		return result
	}

防抖函数

触发高频事件后,n秒内只会触发一次,如果n秒内高频事件再次被触发,则重新计时;重在清零,相当于只执行最后一次;
常用的场景:
调整浏览器窗口大小,resize次数过于频繁;文本编辑实时保存;搜索框input查询

	debounce(fn,wait){
	  let timer = null
	  return function (){
	    let context = this;
	    if(timer){
	    	clearTimeout(timer)
	    }
	    
	    timer = setTimeout(() => {
	      fn.apply(context,arguments)
	    }, wait);
	  }
	}

节流函数

高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数执行的频率;重在开锁关锁,相当于执行第一次;
常用的场景:
登录、发短信等多次快速点击;

	throttle(fn,wait){
	  let timer;
	  return function () {
	    if (timer != null) return;
	    let context = this;
	    let args = arguments;
	    fn.apply(context, args);
	    timer = setTimeout(() => {
	      timer = null;
	    }, wait);
	  }
	}

使用

methods:{
	handleClick:debounce(function(){
		// xxxx
	},2000)
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值