深拷贝对象或数组
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)
}