#Listen to events
We can usev-on
Instructions (usually abbreviated as@
Symbol) to listen for DOM events and execute some when the event is triggeredJavaScript. Usage isv-on:click="methodName"
Or use shortcuts@click="methodName"
For example:
<div >
<button @click="counter += 1">Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
</div>
({
data() {
return {
counter: 1
}
}
}).mount('#basic-event')
result:Click here to implement
#Event handling method
However, many event processing logics are more complicated, so I directly write the JavaScript code inv-on
It is not feasible in the instruction. thereforev-on
You can also receive a method name that needs to be called.
For example:
<div >
<!-- `greet` method name defined below -->
<button @click="greet">Greet</button>
</div>
({
data() {
return {
name: ''
}
},
methods: {
greet(event) {
// `this` internal `methods` point to the currently active instance
alert('Hello ' + + '!')
// `event` is native DOM event
if (event) {
alert()
}
}
}
}).mount('#event-with-method')
result:Click here to implement
#InlineMethods in the processor
In addition to directly binding to a method, you can also call methods in inlined JavaScript statements:
<div >
<button @click="say('hi')">Say hi</button>
<button @click="say('what')">Say what</button>
</div>
({
methods: {
say(message) {
alert(message)
}
}
}).mount('#inline-handler')
result:Click here to implement
Sometimes it is also necessary to access the original DOM event in the inline statement processor. Special variables can be used$event
Pass it into the method:
<button @click="warn('Form cannot be submitted yet.', $event)">
Submit
</button>
// ...
methods: {
warn(message, event) {
// now we have access to the native event
if (event) {
()
}
alert(message)
}
}
#Multi-event handler
There can be multiple methods in the event handler, and these methods areComma operatorSeparation:
<!-- These two one() and two() will execute the button click event -->
<button @click="one($event), two($event)">
Submit
</button>
// ...
methods: {
one(event) {
// first handler logic...
},
two(event) {
// second handler logic...
}
}
#Event modifier
Called in event handler()
or()
It is a very common requirement. Although we can easily achieve this in methods, a better way is: the method has only pure data logic, rather than dealing with DOM event details.
To solve this problem,forv-on
ProvidedEvent modifier. As mentioned earlier, the modifier is represented by the suffix of the instruction starting with a dot.
.stop
.prevent
.capture
.self
.once
.passive
<!-- Prevent click events from continuing to propagate -->
<a @="doThis"></a>
<!-- Submit event no longer reloads the page -->
<form @="onSubmit"></form>
<!-- Modifiers can be concatenated -->
<a @="doThat"></a>
<!-- Only modifiers -->
<form @></form>
<!-- Use event capture mode when adding event listeners -->
<!-- That is, the events triggered by the internal element are processed here first, and then handed over to the internal element for processing -->
<div @="doThis">...</div>
<!-- The processing function is triggered only when it is the current element itself -->
<!-- i.e. events are not triggered from internal elements -->
<div @="doThat">...</div>
TIP
When using modifiers, the order is important; the corresponding code will be generated in the same order. Therefore, usev-on:
will block all clicks, andv-on:
It will only prevent clicks on the element itself.
<!-- The click event will only be triggered once -->
<a @="doThis"></a>
Unlike other modifiers that can only work on native DOM events,.once
Modifiers can also be used for customizationComponent Eventssuperior. If you haven't read aboutComponentsThere is no need to worry about the documentation now.
VueAlso correspondingThe passive option in addEventListenerProvided.passive
Modifier.
<!-- The default behavior of the scroll event (i.e. the scrolling behavior) will be triggered immediately -->
<!-- without waiting for `onScroll` to complete -->
<!-- This includes the case where `()` -->
<div @="onScroll">...</div>
this.passive
Modifiers can especially improve mobileperformance。
TIP
Don't put it.passive
and.prevent
Use together because.prevent
It will be ignored, and the browser may show you a warning. Please remember,.passive
Will tell the browser youIn no moodThe default behavior of blocking events.
#Key modifier
ListeningKeyboard eventsWhen we often need to check detailed keys. Vue allowsv-on
or@
Add key modifiers when listening for keyboard events:
<!-- `()` is called only if `key` is `Enter` -->
<input @="submit" />
You can directlyAny exposed valid key name is converted to kebab-case as a modifier.
<input @-down="onPageDown" />
In the above example, the processing function will only be$
Equal to'PageDown'
is called when .
#Key alias
Vue provides alias for the most commonly used keys:
.enter
.tab
-
.delete
(Capture the "Delete" and "Backspace" keys) .esc
.space
.up
.down
.left
.right
#System Modification Key
The following modifier can be used to implement a listener that triggers a mouse or keyboard event only when the corresponding key is pressed.
.ctrl
.alt
.shift
.meta
hint
Note: On the Mac system keyboard, meta corresponds to the command key (⌘). existWindowsSystem keyboard meta corresponds to Windows logo keys (⊞). On the Sun operating system keyboard, meta corresponds to the solid gem key (◆). On other specific keyboards, especially on the keyboards of MIT and Lisp machines, and their successors, such as the Knight keyboard and the space-cadet keyboard, meta is marked "META". On the Symbolics keyboard, meta is marked as "META" or "Meta".
For example:
<!-- Alt + Enter -->
<input @="clear" />
<!-- Ctrl + Click -->
<div @="doSomething">Do something</div>
TIP
Please note that the modifier key is different from the regular key, andkeyup
When events are used together, the modifier key must be pressed when the event is triggered. In other words, only press and holdctrl
In the case of release other buttons to trigger. And just release
ctrl
Events will not be triggered.
#.exact
Modifier
.exact
Modifiers allow you to control events triggered by precise combinations of system modifiers.
<!-- Triggers even when Alt or Shift is pressed together -->
<button @="onClick">A</button>
<!-- There is and only triggers when Ctrl is pressed -->
<button @="onCtrlClick">A</button>
<!-- Triggered only when no system modifier is pressed -->
<button @="onClick">A</button>
#Mouse button modifier
.left
.right
.middle
These modifiers restrict the processing function to respond only to specific mouse buttons.
#Why listen for events in HTML?
You may have noticed that this kind of event monitoring goes against the long-standing tradition of separation of concern. But don't worry, because all event handling methods and expressions are strictly bound to the ViewModel of the current view, which will not cause any maintenance difficulties. In fact, usev-on
or@
There are several benefits:
- Scan the HTML template to easily locate the corresponding methods in JavaScript code.
- Because you don't have to manually bind events in JavaScript, your ViewModel code can be very pure logic, completely decoupled from the DOM, making it easier to test.
- When a ViewModel is destroyed, all event processors are automatically deleted. You don't have to worry about how to clean them up.