在 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


版权声明:本文为qq_35385241原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。