函数节流与防抖
函数的节流与防抖使用的时候一般会通过throttle或debounce方法对需要调用的函数进行封装,下面使用的是lodash提供的方法,也可以自行实现节流防抖
1. 安装lodash工具库
npm install lodash -S
或
cnpm install lodash -S
2. 新建js文件并定义一个工具类
import { throttle, debounce } from "lodash";
class Decorator {
/*
* 函数节流
* @param { number } wait 节流时间(毫秒)
* @param { Object } options 节流选项对象
* [options.leading] Boolean 指定调用在节流开始前
* [options.trailing] Boolean 指定调用在节流结束后
*/
throttle(wait, options = {}) {
return (target, name, descriptor) => descriptor.value = throttle(descriptor.value, wait, options)
}
/*
* 函数防抖
* @param { number } wait 节流时间(毫秒)
* @param { Object } options 节流选项对象
* [options.leading] Boolean 指定调用在节流开始前
* [options.maxWait] Number func 允许被延迟的最大值
* [options.trailing] Boolean 指定调用在节流结束后
*/
debounce(wait, options = {}) {
return (target, name, descriptor) => descriptor.value = debounce(descriptor.value, wait, options)
}
}
// 实例化后再导出
export default new Decorator();
3. 在组件中使用
import { debounce } from "@/decorator";
export default {
methods:{
@debounce(100)
resize(){}
}
}