beka
5/7/2019 - 5:33 PM

防抖、 debounce

<template>
  <div>
    <input v-model="text" ref="input">
    <p>{{debounceText}}</p>
  </div>
</template>

<script>
export default {
  name: "debounce",
  data() {
    return {
      text: "",
      debounceText: ""
    };
  },
  mounted() {
    let input = this.$refs.input;
    // 在这里绑定一次
    input.addEventListener("input", this.debounce(this.inputVal, 3000));
  },
  methods: {
    inputVal(event) {
      this.debounceText = event.target.value;
    },
    // 防抖函数
    debounce(handler, delay) {
      let timer = null;
      return function() {
        let that = this;
        let arg = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
          handler.apply(that, arg);
        }, delay);
      };
    }
  }
};
</script>
<style lang='scss' scoped>
</style>