在 Vue 中正确使用 防抖 和 节流

1. 观察者防抖

1. 在 create() 钩子 里,创建 防抖回调,并将其赋值到实例上:this.debouncedWatch = debounce(…, 500)。
2. 在 观察者 回调 watch.value() { … } 中 传入正确的参数 调用 this.debouncedWatch()。
3. 最后,beforeUnmount() 钩子中 调用 this.debouncedWatch.cancel() ,在卸载组件之前,取消所有还在 pending 的 防抖函数执行。
<template>
  <input v-model="value" type="text" />
  <p>{{ value }}</p>
</template>
<script>
import  _ from "lodash";
export default {
  data() {
    return {
      value: "",
    };
  },
  watch: {
    value(...args) {
      this.debouncedWatch(...args);
    },
  },
  created() {
    this.debouncedWatch = _.debounce((newValue, oldValue) => {
      console.log('New value:', newValue);
    }, 500);
  },
  beforeUnmount() {
    this.debouncedWatch.cancel();
  },
};
</script>

2. 事件处理器 防抖

1. 在 create() 钩子 里,创建实例后,立刻将 防抖回调 debounce(event => {…}, 500) 赋值到 this.debouncedHandler 。
2. 在输入框的 template 中 给 v-on:input 赋上 debouncedHandler :
3. 最后,在卸载组件之前, 在 beforeUnmount() 钩子中 调用 this.debouncedHandler.cancel() ,取消所有还在 pending 的 函数调用。
<template>
  <input v-on:input="debouncedHandler" type="text" />
</template>
<script>
import _ from "lodash";
export default {
  created() {
    this.debouncedHandler = _.debounce(event => {
      console.log('New value:', event.target.value);
    }, 500);
  },
  beforeUnmount() {
    this.debouncedHandler.cancel();
  }
};
</script>

参考: https://juejin.cn/post/7034458741990752287

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值