VUE中通过method和watch实现防抖的两种方式

概述:

防抖是指指触发事件后,在 n 秒内函数只能执行一次,如果触发事件后在 n 秒内又触发了事件,则会重新计算函数延执行时间。

防抖应用场景:

有一些事件,常见的例如,keypress/keyup,onresize,scroll,mousemove ,mousehover 等,会被频繁触发(短时间内多次触发),不做限制的话,有可能一秒之内执行几十次、几百次,如果在这些函数内部执行了其他函数,尤其是执行了操作 DOM 的函数(浏览器操作 DOM 是很耗费性能的),那不仅会浪费计算机资源,还会降低程序运行速度,甚至造成浏览器卡死、崩溃。这种问题显然是致命的。

如何定义防抖方法:

需要一个 setTimeout 来辅助实现,延迟运行需要执行的代码。如果方法多次触发,则把上次记录的延迟执行代码用 clearTimeout 清掉,重新开始计时。若计时期间事件没有被重新触发,等延迟时间计时完毕,则执行目标代码。


const debounce = function debounce(fn, delay) {
    var timeoutID = null;
    return function () {
      clearTimeout(timeoutID);
      var args = arguments;
      var that = this;
      timeoutID = setTimeout(function () {
        fn.apply(that, args);
      }, delay);
    };
  };

VUE中method和watch区别

1.watch:watch是以Vue的依赖追踪机制为基础的,它试图处理当某一个数据(称它为依赖数据)发生变化的时候,所有依赖这个数据的“相关”数据“自动”发生变化,也就是自动调用相关的函数去实现数据的变动。

2.对methods:methods里面是用来定义函数的,很显然,它需要手动调用才能执行。而不像watch和computed那样,“自动执行”预先定义的函数。

通过method实现的防抖:

<template>
  <div>
    <input type="text" v-model="input_text" />
    <button @click="input">点我</button>
    <br />
    {{ debounced_input }}
  </div>
</template>

<script>
  const debounce = function debounce(fn, delay) {
    var timer = null;
    return function () {
      clearTimeout(timer);
      var args = arguments;
      var that = this;
      timer = setTimeout(function () {
        fn.apply(that, args);
      }, delay);
    };
  };

  export default {
    name: 'test_debounce',
    data() {
      return {
        input_text: "",
        debounced_input: ""
      };
    },
    methods:{
      input: debounce(function () {
        this.debounced_input = this.$data.input_text;
      }, 500)
    },
  };
</script>

通过watch实现的防抖

<template>
  <div>
    <input type="text" v-model="input_text" />
    <br />
    {{ debounced_input }}
  </div>
</template>

<script>
  const debounce = function debounce(fn, delay) {
    var timer = null;
    return function () {
      clearTimeout(timer);
      var args = arguments;
      var that = this;
      timer = setTimeout(function () {
        fn.apply(that, args);
      }, delay);
    };
  };

  export default {
    name: 'test_debounce',
    data() {
      return {
        input_text: "",
        debounced_input: ""
      };
    },

    watch: {
      input_text: debounce(function (new_value) {
        this.debounced_input = new_value;
      }, 500)
    }
  };
</script>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容