vue2 debounce 实现

最近在看vue2 发现了一个有趣的事情,就是在vue2里面很多属性都不能用比如:

vue2 debounce 实现

debounce 这个属性是不能再vue2里面使用的的,但是在现实情况下又需要,比如在执行input 事件当中执行ajax的时候

就需要限制输入间隔,废话不多说,上代码:

<template>
  <div>
    <div>
      <input type="text" name="" id="inputValue" v-model="inputValue">
    </div>
    <div class="after">
      <p>{{inputValue}}</p>
    </div>
    <div class="before">
      <p>{{afterValue}}</p>
    </div>
  </div>
</template>


<script>
  import $ from 'jquery'
  import Vue from 'vue'
  export default {
    name: 'debounce',
    data () {
      return {
        inputValue: '',
        afterValue: ''
      }
    },
    methods: {
      changeData: function () {
        this.afterValue = this.inputValue 
      }
    },
    mounted: function () {
      var _t = this
      this.$nextTick(function () {
        $("#inputValue").on('input', debounce(function (e) {
          _t.changeData()
        }, 500))
        function debounce (fn, delay) {
          var timer = null
          return function () {
            var context = this
            var args = arguments
            clearTimeout(timer)
            timer = setTimeout(function () {
              fn.apply(context, args)
            }, delay)
          }
        }
      })
    }
  }

</script>

vue2 debounce 实现

这是整个代码的核心,当执行input 事件的时候在mouted 绑定一个钩子函数,在每次输入的时候返回一个 闭包。闭包在每次输入的时候清除上一次的定时器,在规定时间之内只能执行一次代码...so easy