Vue函数节流与防抖(使用工具库lodash)

函数节流与防抖

函数的节流与防抖使用的时候一般会通过throttledebounce方法对需要调用的函数进行封装,下面使用的是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(){}
  }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue使用lodash来实现节流防抖的方法如下: 1. 安装lodash:在项目根目录下打开命令行工具,执行以下命令安装lodash: ``` npm install lodash ``` 2. 导入lodash:在需要使用节流防抖的组件,导入lodash的相关函数: ```javascript import { debounce, throttle } from 'lodash'; ``` 3. 使用节流函数使用`throttle`函数来实现节流。`throttle`函数会在指定的时间间隔内只执行一次函数,可以用于限制频繁触发的事件,例如滚动、拖拽等。以下是一个使用节流函数的示例: ```javascript export default { data() { return { scrollHandler: null }; }, methods: { handleScroll() { // 处理滚动事件的逻辑 console.log('Scroll event'); } }, mounted() { this.scrollHandler = throttle(this.handleScroll, 200); // 设置节流时间为200ms window.addEventListener('scroll', this.scrollHandler); }, beforeDestroy() { window.removeEventListener('scroll', this.scrollHandler); } } ``` 在上述代码使用`throttle`函数将`handleScroll`方法包装起来,设置节流时间为200ms。在组件的`mounted`生命周期钩子,将节流后的处理函数添加到`scroll`事件监听器,保证在指定时间间隔内只执行一次。 4. 使用防抖函数使用`debounce`函数来实现防抖。`debounce`函数会在指定的时间间隔后执行函数,如果在这个时间间隔内又触发了同样的函数,则重新计时。以下是一个使用防抖函数的示例: ```javascript export default { data() { return { inputHandler: null, inputValue: '' }; }, methods: { handleInput() { // 处理输入事件的逻辑 console.log('Input event'); } }, mounted() { this.inputHandler = debounce(this.handleInput, 500); // 设置防抖时间为500ms } } ``` 在上述代码使用`debounce`函数将`handleInput`方法包装起来,设置防抖时间为500ms。在组件的`mounted`生命周期钩子,将防抖后的处理函数赋值给`inputHandler`。 在模板,将防抖处理函数绑定到相应的事件上: ```html <input type="text" v-model="inputValue" @input="inputHandler"> ``` 这样,在输入框输入内容时,只有在500ms内没有再次输入才会触发防抖后的处理函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值