Guide
- Installation
- Getting Started
- Overview
- The Vue Instance
- Data Binding Syntax
- Computed Properties
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Methods and Event Handling
- Form Input Bindings
- Transitions
- Components
- Reactivity in Depth
- Custom Directives
- Custom Filters
- Mixins
- Plugins
- Building Large-Scale Apps
- Comparison with Other Frameworks
- Join the Vue Community!
Methods and Event Handling
Method Handler
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:
Inline Statement Handler
Instead of binding directly to a method name, we can also use an inline JavaScript statement:
|
|
Result:
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:
|
|
Event Modifiers
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:
|
In 1.0.16, two additional modifiers have been introduced:
|
Key Modifiers
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:
- enter
- tab
- delete (captures both “Delete” and, if the keyboard has it, “Backspace”)
- esc
- space
- up
- down
- left
- right
1.0.8+: Single letter key aliases are also supported.
1.0.17+: You can also define custom key modifier aliases:
|
Why Listeners in HTML?
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 v-on
:
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.