beka
5/7/2019 - 6:04 PM

节流、 throttle

<template>
  <div>
    <input v-model="text" ref="input">
  </div>
</template>

<script>
export default {
  name: "throttle",
  data() {
    return {
      text: "",
    };
  },
  mounted() {
    let input = this.$refs.input;
    // 在这里绑定一次
    input.addEventListener("input", this.throttle(this.inputVal, 3000));
  },
  methods: {
    inputVal(event) {
      console.log ('执行了', event.target.value)
    },
    // 防抖函数
    // 每次执行都要等wait时间:多用于拖拽,防多次点击
    throttle(handler, wait) {
      let lastTime = 0
      return function() {
        let nowTime = (new Date()).getTime()
        if (nowTime - lastTime >= wait) {
          handler.apply(this, arguments)
          lastTime = nowTime
        }
      }
    }
  }
};
</script>
<style lang='scss' scoped>
</style>