[Vuejs]-Vue returning methods inline

3👍

Vue element bindings will evaluate expressions, but an expression using the return keyword makes it impossible for Vue to execute, correctly.

Vue bindings are happy taking method references. So what you’d technically want is:

<input type="text" name="someid" @keypress="isNumberKey" />

Notice that we also removed the expression actually invoking isNumberKey($event). Simply, providing a reference to the method, Vue will call isNumberKey and pass it an Event object as the first argument.

Now, I’m not sure if simply returning false will cancel the keypress (if it does, please leave me a comment). But I’m sure that using preventDefault() will do the trick, so you could technically rewrite your function as follows:

isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    evt.preventDefault();
}

Leave a comment