This is undefined in Vue, using debounce method

Viewed 1246

I know that using the arrow syntax for a method will cause 'this' to not be mapped to the Vue instance, however in my example I'm using lodash.debounce, and as far as I know I'm not using the arrow syntax here?

Returns Cannot read property '$emit' of undefined

methods: {
  onChange: debounce(function(el) {
    this.$emit('change', el.target.value)
  }, 1000)
}

is there a syntax error in the way I'm writing this debounce function without arrow notation?

1 Answers

Your code should be working. Can you provide some additional context?

A slight improvement: it's usually best to create the debounced function per instance rather than sharing one across all instances of that component.

methods: {
  onChange(e) {
    this.$emit('change', e.target.value)
  }
},

created() {
  this.onChange = _.debounce(this.onChange, 1000)
}

Here's a working example:

new Vue({
  el: '#app',
  
  data: {
    text: '',
  },
  
  created() {
    this.onClick = _.debounce(this.onClick, 1000)
  },
  
  methods: {
    onClick() {
      // this is not undefined here
      this.text += 'Debounced! ';
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="onClick">Click Me</button>
  <p>{{ text }}</p>
</div>

Related