YouTip LogoYouTip

Vue3 V On

## Vue3 v-on Directive The `v-on` directive is a core Vue.js directive used to bind event listeners to elements. It allows you to listen to native DOM events (such as clicks, form submissions, and keyboard inputs) as well as custom events emitted by child components. --- ## Overview and Syntax * **Shorthand**: `@` * **Expected Value Type**: `Function` | `Inline Statement` | `Object` * **Purpose**: Attaches an event listener to an element or component. ### Syntax Comparison You can use either the full `v-on:` syntax or the highly popular `@` shorthand: ```html ``` --- ## Basic Usage The `v-on` directive can execute inline JavaScript statements directly, or point to a method defined in your component. ### 1. Inline Statement Example For simple state changes, you can write expressions directly inside the directive: ```html ``` ### 2. Method Handler Example For more complex logic, you should bind the event to a component method: ```html ``` --- ## Event Modifiers Vue provides **Event Modifiers** to handle common DOM event details (like calling `event.preventDefault()` or `event.stopPropagation()`) directly inside your templates. This keeps your method logic pure and focused on data rather than DOM details. Modifiers are appended to the directive name with a dot: ```html
``` --- ## Key Modifiers When listening for keyboard events, you can check for specific keys. Vue provides aliases for the most common keys: ```html ``` ### Common Key Aliases: * `.enter` * `.tab` * `.delete` (captures both "Delete" and "Backspace" keys) * `.esc` * `.space` * `.up` * `.down` * `.left` * `.right` --- ## System Modifier Keys You can use the following modifiers to trigger mouse or keyboard event listeners only when the corresponding system modifier key is pressed: * `.ctrl` * `.alt` * `.shift` * `.meta` (Command key on Mac, Windows key on Windows) ```html ``` --- ## Best Practices & Considerations 1. **Keep Templates Clean**: Use inline statements only for trivial operations (like toggling a boolean or incrementing a counter). For anything involving business logic, delegate to a method. 2. **Automatic Event Passing**: If no arguments are passed to a method handler, Vue automatically passes the native DOM `event` object as the first parameter. 3. **Accessing Native Event in Inline Handlers**: If you need to access the native DOM event in an inline statement, you can pass the special `$event` variable: ```html ``` 4. **Component Clean-up**: When a Vue component is unmounted, all event listeners bound via `v-on` are automatically removed. You do not need to worry about manual clean-up for these template-bound events.
← Vue3 V PreVue3 V Memo β†’