|
| 1 | +# Event Handling |
| 2 | + |
| 3 | +<div class="vueschool"><a href="https://vueschool.io/lessons/vuejs-user-events?friend=vuejs" target="_blank" rel="sponsored noopener" title="Learn how to handle events on Vue School">Learn how to handle events in a free Vue School lesson</a></div> |
| 4 | + |
| 5 | +## Listening to Events |
| 6 | + |
| 7 | +We can use the `v-on` directive to listen to DOM events and run some JavaScript when they're triggered. |
| 8 | + |
| 9 | +For example: |
| 10 | + |
| 11 | +```html |
| 12 | +<div id="example-1"> |
| 13 | + <button v-on:click="counter += 1">Add 1</button> |
| 14 | + <p>The button above has been clicked {{ counter }} times.</p> |
| 15 | +</div> |
| 16 | +``` |
| 17 | + |
| 18 | +```js |
| 19 | +Vue.createApp().mount( |
| 20 | + { |
| 21 | + data() { |
| 22 | + return { |
| 23 | + counter: 1 |
| 24 | + } |
| 25 | + } |
| 26 | + }, |
| 27 | + '#example-1' |
| 28 | +) |
| 29 | +``` |
| 30 | + |
| 31 | +Result: |
| 32 | + |
| 33 | +<events-1/> |
| 34 | + |
| 35 | +## Method Event Handlers |
| 36 | + |
| 37 | +The logic for many event handlers will be more complex though, so keeping your JavaScript in the value of the `v-on` attribute isn't feasible. That's why `v-on` can also accept the name of a method you'd like to call. |
| 38 | + |
| 39 | +For example: |
| 40 | + |
| 41 | +```html |
| 42 | +<div id="example-2"> |
| 43 | + <!-- `greet` is the name of a method defined below --> |
| 44 | + <button v-on:click="greet">Greet</button> |
| 45 | +</div> |
| 46 | +``` |
| 47 | + |
| 48 | +```js |
| 49 | +Vue.createApp().mount( |
| 50 | + { |
| 51 | + data() { |
| 52 | + return { |
| 53 | + name: 'Vue.js' |
| 54 | + } |
| 55 | + }, |
| 56 | + methods: { |
| 57 | + greet(event) { |
| 58 | + // `this` inside methods points to the Vue instance |
| 59 | + alert('Hello ' + this.name + '!') |
| 60 | + // `event` is the native DOM event |
| 61 | + if (event) { |
| 62 | + alert(event.target.tagName) |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + }, |
| 67 | + '#example-2' |
| 68 | +) |
| 69 | +``` |
| 70 | + |
| 71 | +Result: |
| 72 | + |
| 73 | +<events-2/> |
| 74 | + |
| 75 | +## Methods in Inline Handlers |
| 76 | + |
| 77 | +Instead of binding directly to a method name, we can also use methods in an inline JavaScript statement: |
| 78 | + |
| 79 | +```html |
| 80 | +<div id="example-3"> |
| 81 | + <button v-on:click="say('hi')">Say hi</button> |
| 82 | + <button v-on:click="say('what')">Say what</button> |
| 83 | +</div> |
| 84 | +``` |
| 85 | + |
| 86 | +```js |
| 87 | +Vue.createApp().mount( |
| 88 | + { |
| 89 | + methods: { |
| 90 | + say(message) { |
| 91 | + alert(message) |
| 92 | + } |
| 93 | + } |
| 94 | + }, |
| 95 | + '#example-3' |
| 96 | +) |
| 97 | +``` |
| 98 | + |
| 99 | +Result: |
| 100 | + |
| 101 | +<events-3/> |
| 102 | + |
| 103 | +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: |
| 104 | + |
| 105 | +```html |
| 106 | +<button v-on:click="warn('Form cannot be submitted yet.', $event)"> |
| 107 | + Submit |
| 108 | +</button> |
| 109 | +``` |
| 110 | + |
| 111 | +```js |
| 112 | +// ... |
| 113 | +methods: { |
| 114 | + warn(message, event) { |
| 115 | + // now we have access to the native event |
| 116 | + if (event) { |
| 117 | + event.preventDefault() |
| 118 | + } |
| 119 | + alert(message) |
| 120 | + } |
| 121 | +} |
| 122 | +``` |
| 123 | + |
| 124 | +## Event Modifiers |
| 125 | + |
| 126 | +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. |
| 127 | + |
| 128 | +To address this problem, Vue provides **event modifiers** for `v-on`. Recall that modifiers are directive postfixes denoted by a dot. |
| 129 | + |
| 130 | +- `.stop` |
| 131 | +- `.prevent` |
| 132 | +- `.capture` |
| 133 | +- `.self` |
| 134 | +- `.once` |
| 135 | +- `.passive` |
| 136 | + |
| 137 | +```html |
| 138 | +<!-- the click event's propagation will be stopped --> |
| 139 | +<a v-on:click.stop="doThis"></a> |
| 140 | + |
| 141 | +<!-- the submit event will no longer reload the page --> |
| 142 | +<form v-on:submit.prevent="onSubmit"></form> |
| 143 | + |
| 144 | +<!-- modifiers can be chained --> |
| 145 | +<a v-on:click.stop.prevent="doThat"></a> |
| 146 | + |
| 147 | +<!-- just the modifier --> |
| 148 | +<form v-on:submit.prevent></form> |
| 149 | + |
| 150 | +<!-- use capture mode when adding the event listener --> |
| 151 | +<!-- i.e. an event targeting an inner element is handled here before being handled by that element --> |
| 152 | +<div v-on:click.capture="doThis">...</div> |
| 153 | + |
| 154 | +<!-- only trigger handler if event.target is the element itself --> |
| 155 | +<!-- i.e. not from a child element --> |
| 156 | +<div v-on:click.self="doThat">...</div> |
| 157 | +``` |
| 158 | + |
| 159 | +::: tip |
| 160 | +Order matters when using modifiers because the relevant code is generated in the same order. Therefore using `v-on:click.prevent.self` will prevent **all clicks** while `v-on:click.self.prevent` will only prevent clicks on the element itself. |
| 161 | +::: |
| 162 | + |
| 163 | +```html |
| 164 | +<!-- the click event will be triggered at most once --> |
| 165 | +<a v-on:click.once="doThis"></a> |
| 166 | +``` |
| 167 | + |
| 168 | +Unlike the other modifiers, which are exclusive to native DOM events, the `.once` modifier can also be used on [component events](TODO:components-custom-events.html). If you haven't read about components yet, don't worry about this for now. |
| 169 | + |
| 170 | +Vue also offers the `.passive` modifier, corresponding to [`addEventListener`'s `passive` option](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters). |
| 171 | + |
| 172 | +```html |
| 173 | +<!-- the scroll event's default behavior (scrolling) will happen --> |
| 174 | +<!-- immediately, instead of waiting for `onScroll` to complete --> |
| 175 | +<!-- in case it contains `event.preventDefault()` --> |
| 176 | +<div v-on:scroll.passive="onScroll">...</div> |
| 177 | +``` |
| 178 | + |
| 179 | +The `.passive` modifier is especially useful for improving performance on mobile devices. |
| 180 | + |
| 181 | +::: tip |
| 182 | +Don't use `.passive` and `.prevent` together, because `.prevent` will be ignored and your browser will probably show you a warning. Remember, `.passive` communicates to the browser that you _don't_ want to prevent the event's default behavior. |
| 183 | +::: |
| 184 | + |
| 185 | +## Key Modifiers |
| 186 | + |
| 187 | +When listening for keyboard events, we often need to check for specific keys. Vue allows adding key modifiers for `v-on` when listening for key events: |
| 188 | + |
| 189 | +```html |
| 190 | +<!-- only call `vm.submit()` when the `key` is `Enter` --> |
| 191 | +<input v-on:keyup.enter="submit" /> |
| 192 | +``` |
| 193 | + |
| 194 | +You can directly use any valid key names exposed via [`KeyboardEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) as modifiers by converting them to kebab-case. |
| 195 | + |
| 196 | +```html |
| 197 | +<input v-on:keyup.page-down="onPageDown" /> |
| 198 | +``` |
| 199 | + |
| 200 | +In the above example, the handler will only be called if `$event.key` is equal to `'PageDown'`. |
| 201 | + |
| 202 | +### Key Codes |
| 203 | + |
| 204 | +::: tip |
| 205 | +The use of `keyCode` events [is deprecated](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) and may not be supported in new browsers. |
| 206 | +::: |
| 207 | + |
| 208 | +Using `keyCode` attributes is also permitted: |
| 209 | + |
| 210 | +```html |
| 211 | +<input v-on:keyup.13="submit" /> |
| 212 | +``` |
| 213 | + |
| 214 | +Vue provides aliases for the most commonly used key codes when necessary for legacy browser support: |
| 215 | + |
| 216 | +- `.enter` |
| 217 | +- `.tab` |
| 218 | +- `.delete` (captures both "Delete" and "Backspace" keys) |
| 219 | +- `.esc` |
| 220 | +- `.space` |
| 221 | +- `.up` |
| 222 | +- `.down` |
| 223 | +- `.left` |
| 224 | +- `.right` |
| 225 | + |
| 226 | +A few keys (`.esc` and all arrow keys) have inconsistent `key` values in IE9, so these built-in aliases should be preferred if you need to support IE9. |
| 227 | + |
| 228 | +You can also [define custom key modifier aliases](TODO:../api/#keyCodes) via the global `config.keyCodes` object: |
| 229 | + |
| 230 | +```js |
| 231 | +// enable `v-on:keyup.f1` |
| 232 | +Vue.config.keyCodes.f1 = 112 |
| 233 | +``` |
| 234 | + |
| 235 | +## System Modifier Keys |
| 236 | + |
| 237 | +You can use the following modifiers to trigger mouse or keyboard event listeners only when the corresponding modifier key is pressed: |
| 238 | + |
| 239 | +- `.ctrl` |
| 240 | +- `.alt` |
| 241 | +- `.shift` |
| 242 | +- `.meta` |
| 243 | + |
| 244 | +::: tip Note |
| 245 | +On Macintosh keyboards, meta is the command key (⌘). On Windows keyboards, meta is the Windows key (⊞). On Sun Microsystems keyboards, meta is marked as a solid diamond (◆). On certain keyboards, specifically MIT and Lisp machine keyboards and successors, such as the Knight keyboard, space-cadet keyboard, meta is labeled “META”. On Symbolics keyboards, meta is labeled “META” or “Meta”. |
| 246 | +::: |
| 247 | + |
| 248 | +For example: |
| 249 | + |
| 250 | +```html |
| 251 | +<!-- Alt + C --> |
| 252 | +<input v-on:keyup.alt.67="clear" /> |
| 253 | + |
| 254 | +<!-- Ctrl + Click --> |
| 255 | +<div v-on:click.ctrl="doSomething">Do something</div> |
| 256 | +``` |
| 257 | + |
| 258 | +::: tip Tip |
| 259 | +Note that modifier keys are different from regular keys and when used with `keyup` events, they have to be pressed when the event is emitted. In other words, `keyup.ctrl` will only trigger if you release a key while holding down `ctrl`. It won't trigger if you release the `ctrl` key alone. If you do want such behaviour, use the `keyCode` for `ctrl` instead: `keyup.17`. |
| 260 | +::: |
| 261 | + |
| 262 | +### `.exact` Modifier |
| 263 | + |
| 264 | +The `.exact` modifier allows control of the exact combination of system modifiers needed to trigger an event. |
| 265 | + |
| 266 | +```html |
| 267 | +<!-- this will fire even if Alt or Shift is also pressed --> |
| 268 | +<button v-on:click.ctrl="onClick">A</button> |
| 269 | + |
| 270 | +<!-- this will only fire when Ctrl and no other keys are pressed --> |
| 271 | +<button v-on:click.ctrl.exact="onCtrlClick">A</button> |
| 272 | + |
| 273 | +<!-- this will only fire when no system modifiers are pressed --> |
| 274 | +<button v-on:click.exact="onClick">A</button> |
| 275 | +``` |
| 276 | + |
| 277 | +### Mouse Button Modifiers |
| 278 | + |
| 279 | +- `.left` |
| 280 | +- `.right` |
| 281 | +- `.middle` |
| 282 | + |
| 283 | +These modifiers restrict the handler to events triggered by a specific mouse button. |
| 284 | + |
| 285 | +## Why Listeners in HTML? |
| 286 | + |
| 287 | +You might be concerned that this whole event listening approach violates the good old rules about "separation of concerns". Rest assured - since all Vue 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`: |
| 288 | + |
| 289 | +1. It's easier to locate the handler function implementations within your JS code by skimming the HTML template. |
| 290 | + |
| 291 | +2. 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. |
| 292 | + |
| 293 | +3. When a ViewModel is destroyed, all event listeners are automatically removed. You don't need to worry about cleaning it up yourself. |
0 commit comments