Vue V On V Bind

Posted on  by admin
You’re browsing the documentation for v2.x and earlier.

For v3.x, click here. We can use the v-on directive to listen to DOM events and run some JavaScript when they’re triggered.

$('#myDiv').on('touchstart mousedown', // more code here

The button above has been clicked {{ counter }} times. 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. Instead of binding directly to a method name, we can also use methods in an inline JavaScript statement:.

Ben ClarkeBen Clarke
1,017

System Modifier Keys

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.

Modifiers

To address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot. Order matters when using modifiers because the relevant code is generated in the same order.

Why Listeners in HTML?

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.

Unlike the other modifiers, which are exclusive to native DOM events, the .once modifier can also be used on component events. If you haven’t read about components yet, don’t worry about this for now. Vue also offers the .passive modifier, corresponding to addEventListener‘s passive option.

The .passive modifier is especially useful for improving performance on mobile devices. Don’t use .passive and .prevent together, because .prevent will be ignored and your browser will probably show you a warning.

Yom T.Yom T.
7,4972

Vue allows adding key modifiers for v-on when listening for key events:. You can directly use any valid key names exposed via KeyboardEvent.key as modifiers by converting them to kebab-case. In the above example, the handler will only be called if $event.key is equal to 'PageDown'.

The use of keyCode events is deprecated and may not be supported in new browsers. Using keyCode attributes is also permitted:.

Vue provides aliases for the most commonly used key codes when necessary for legacy browser support:.
2

.delete (captures both “Delete” and “Backspace” keys). 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.

You can also define custom key modifier aliases via the global config.keyCodes object:.

You can use the following modifiers to trigger mouse or keyboard event listeners only when the corresponding modifier key is pressed:.

Note: On Macintosh keyboards, meta is the command key (⌘).

vzwickvzwick
10.7k6

Not the answer you're looking for? Browse other questions tagged javascriptjqueryvue.jsvuejs2 or ask your own question.