Search code examples
javascriptvue.jslodash

How to access event object in a method with debounce - Vue


Can't get event object in a debounced method:

methods: {
  fetchData: _.debounce(function(e) {
    console.log(e) // return undefined
  }, 500)
}

Is it possible to access event object in a method? My purpose is to check, what keycodes what pressed:

if (e.keyCode >= 65 && e.keyCode <= 80) {
  // do some stuff
}

I call method fetchData this way:

<input @keyup="fetchData()" v-model="name" type="text">

Solution

  • Here is the vue js example, missing @keyup="fetchData($event)" passing event into debounce

    new Vue({
      el: '#app',
      data() {
        return {
          keywords: ''
        }
      },
      methods: {
        fetchData: _.debounce(function(e) {
          console.log(e.keyCode) // return undefined
        }, 500)
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
    <div id="app">
      <input id="textInput" @keyup="fetchData($event)" />
    </div>