//1.与router文件并列新建一个utils/unils.js,在里面编写页面防抖方法
// 用于存储工具方法
export default {
debounce (fn, wait, time) {
var previous = null // 记录上一次运行的时间
var timer = null
return function () {
var now = +new Date()
if (!previous) previous = now
// 当上一次执行的时间与当前的时间差大于设置的执行间隔时长的话,就主动执行一次
if (now - previous > time) {
clearTimeout(timer)
fn()
previous = now // 执行函数后,马上记录当前时间
} else { // 否则重新开始新一轮的计时
clearTimeout(timer)
timer = setTimeout(function () {
fn()
}, wait)
}
}
},
throttle (fn, time) {
let _self = fn
let timer = ''
let firstTime = true // 记录是否是第一次执行的flag
return function () {
let args = arguments // 解决闭包传参问题
let _me = this // 解决上下文丢失问题
if (firstTime) { // 若是第一次,则直接执行
_self.apply(_me, args)
firstTime = false
return
}
if (timer) { // 定时器存在,说明有事件监听器在执行,直接返回
return false
}
timer = setTimeout(function () {
clearTimeout(timer)
timer = null
_self.apply(_me, args)
}, time || 500)
}
},
}
//2.在页面调用
// 监听页面滚动防抖
this.addEvent(document, 'scroll', this.$utils.debounce(this.tableScroll, 100))
// 输入搜索节流 [左侧栏输入搜索]
let searchOrgan = document.getElementById('searchOrgan') //获取搜索框
this.addEvent(searchOrgan, 'keyup', this.$utils.throttle(this.searchOrganEven, 300))