Vue Event Handling
We can use the v-on directive (usually abbreviated as the @ symbol) to listen to DOM events and run some JavaScript code when triggered. This allows us to create interactive user interfaces.
Listening to Events
Usage is v-on:click="methodName" or using the shorthand @click="methodName".
Inline Event Handlers
Besides directly binding to a method, you can also execute simple statements in inline handlers:
Passing Parameters in Methods
When handling events, you often need to pass parameters to the method.
Accessing Event Arguments
Sometimes, we need to access the original DOM event object. You can use the special $event variable to pass it into the method:
Event Modifiers
When handling events, we often need to call event.preventDefault() or event.stopPropagation(). To solve this problem, Vue provides event modifiers for v-on. Modifiers are directive suffixes starting with a dot.
.stop: Callsevent.stopPropagation()..prevent: Callsevent.preventDefault()..capture: Adds event listener in capture mode..self: Only triggers callback when the event is triggered from the element to which the listener is bound itself..once: Click event will only trigger once..passive: Tells the browser you don't want to prevent the event's default behavior.
Key Modifiers
When listening to keyboard events, we often need to check for specific keys. Vue allows adding key modifiers to v-on when listening to keyboard events:
Vue provides aliases for the most commonly used keys:
.enter.tab.delete(captures both "Delete" and "Backspace" keys).esc.space.up.down.left.right
You can also directly use any valid key name as a modifier, for example @keyup.page-down.