- Getting Started
- The Vue Instance
- Data Binding Syntax
- Computed Properties
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Methods and Event Handling
- Form Input Bindings
- Reactivity in Depth
- Custom Directives
- Custom Filters
- Building Large-Scale Apps
- Comparison with Other Frameworks
- Join the Vue Community!
Methods and Event Handling
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:
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
It is a very common need to call
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
.stop. Recall that modifiers are directive postfixes denoted by a dot:
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:
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”. Rest assured - since all Vue.js handler functions and expressions are strictly bound to the ViewModel that’s handling the current View, it won’t cause any maintenance difficulty. In fact, there are several benefits in using
It makes it easier to locate the handler function implementations within your JS code by simply skimming the HTML template.
Since you don’t have to manually attach event listeners in JS, your ViewModel code can be pure logic and DOM-free. This makes it easier to test.
When a ViewModel is destroyed, all event listeners are automatically removed. You don’t need to worry about cleaning it up yourself.