优点:
1、可以在methods方法中直接调用,无需重新定义方法承载,业务逻辑无需拆分;(调用方式在本文末尾)
2、可全局引入直接调用,无需其他操作;
/*
* fun [function] 需要防抖的函数
* delay [number] 毫秒,防抖期限值
*/
export let debounce = (() => {
let instances = []
return function (fun, delay = 300) {
const stackLines = new Error().stack.split('\n');
let callerLine = stackLines[2];
let index = instances.findIndex(item => {
return item.callerLine == callerLine
})
if (index < 0) {
instances.push({ callerLine, fun, delay, timer: null })
index = instances.length - 1
} else {
instances[index].fun = fun
}
let instance = instances[index]
let ctx = this
let args = arguments
if (instance.timer) {
clearTimeout(instance.timer)
}
instance.timer = setTimeout(() => {
instance.timer = null
instance.fun.apply(ctx, args)
instance
}, instance.delay)
}
})()
/*
* fun [function] 需要节流的函数
* delay [number] 毫秒,节流期限值
*/
export let throttle = (() => {
let instances = []
return function (fun, delay = 300) {
const stackLines = new Error().stack.split('\n');
let callerLine = stackLines[2];
let index = instances.findIndex(item => {
return item.callerLine == callerLine
})
if (index < 0) {
instances.push({ callerLine, fun, delay, timeout: null })
index = instances.length - 1
} else {
instances[index].fun = fun
}
let instance = instances[index]
let args = arguments;//注意如果要传参的话 这句不能省略
if (!instance.timeout) {
instance.timeout = setTimeout(() => {
instance.timeout = null;
instance.fun.apply(this, args)
}, instance.delay)
}
}
})()
两个自执行函数放在了utils文件夹下index.js文件中,通过
import * as Util from '@/utils'
Vue.prototype.$util = Util
进行了全局挂载,可根据实际情况需要进行引入或者全局挂载
调用方式
input、button中绑定方式
<el-button size="mini" @click="$util.debounce(infraSetFocus, 300)">测试</el-button>
methods方法中调用方式
methods: {
//....
test() {//频繁调用函数
// 一些其他逻辑......
this.$util.debounce(() => {
// 防抖逻辑
}, 2000)
},
}