Vue Js Event Listener

Posted on  by admin
We can use the v-on directive to listen to DOM events:.

We are binding a click event listener to a method named greet. Here’s how to define that method in our Vue instance:. Test it yourself:. Instead of binding directly to a method name, we can also use an inline JavaScript statement:.

Similar to the restrictions on inline expressions, event handlers are restricted to one statement only.

Sometimes we also need to access the original DOM event in an inline statement handler.

You can pass it into a method using the special $event variable:. It is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers.

Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.

To address this problem, Vue.js provides two event modifiers for v-on: .prevent and .stop.
Recall that modifiers are directive postfixes denoted by a dot:.
6

In 1.0.16, two additional modifiers have been introduced:. When listening for keyboard events, we often need to check for common key codes.

Vue.js also allows adding key modifiers for v-on when listening for key events:. Remembering all the keyCodes is a hassle, so Vue.js provides aliases for most commonly used keys:.

Here’s the full list of key modifier aliases:.

delete (captures both “Delete” and, if the keyboard has it, “Backspace”).

1.0.8+: Single letter key aliases are also supported. 1.0.17+: You can also define custom key modifier aliases:.

You might be concerned that this whole event listening approach violates the good old rules about “separation of concern”.

Void RayVoid Ray
9,2311

Not the answer you're looking for? Browse other questions tagged javascriptvue.jsvuejs2vue-component or ask your own question.