web123456

Vue 3.0 Event Handling [Vue3 Starts from Scratch]

#Listen to events

We can usev-onInstructions (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:

 
  1. <div >
  2. <button @click="counter += 1">Add 1</button>
  3. <p>The button above has been clicked {{ counter }} times.</p>
  4. </div>

 
  1. ({
  2. data() {
  3. return {
  4. counter: 1
  5. }
  6. }
  7. }).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-onIt is not feasible in the instruction. thereforev-onYou can also receive a method name that needs to be called.

For example:

 
  1. <div >
  2. <!-- `greet` method name defined below -->
  3. <button @click="greet">Greet</button>
  4. </div>

 
  1. ({
  2. data() {
  3. return {
  4. name: ''
  5. }
  6. },
  7. methods: {
  8. greet(event) {
  9. // `this` internal `methods` point to the currently active instance
  10. alert('Hello ' + + '!')
  11. // `event` is native DOM event
  12. if (event) {
  13. alert()
  14. }
  15. }
  16. }
  17. }).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:

 
  1. <div >
  2. <button @click="say('hi')">Say hi</button>
  3. <button @click="say('what')">Say what</button>
  4. </div>

 
  1. ({
  2. methods: {
  3. say(message) {
  4. alert(message)
  5. }
  6. }
  7. }).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$eventPass it into the method:

 
  1. <button @click="warn('Form cannot be submitted yet.', $event)">
  2. Submit
  3. </button>

 
  1. // ...
  2. methods: {
  3. warn(message, event) {
  4. // now we have access to the native event
  5. if (event) {
  6. ()
  7. }
  8. alert(message)
  9. }
  10. }

#Multi-event handler

There can be multiple methods in the event handler, and these methods areComma operatorSeparation:

 
  1. <!-- These two one() and two() will execute the button click event -->
  2. <button @click="one($event), two($event)">
  3. Submit
  4. </button>

 
  1. // ...
  2. methods: {
  3. one(event) {
  4. // first handler logic...
  5. },
  6. two(event) {
  7. // second handler logic...
  8. }
  9. }

#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-onProvidedEvent modifier. As mentioned earlier, the modifier is represented by the suffix of the instruction starting with a dot.

  • .stop
  • .prevent
  • .capture
  • .self
  • .once
  • .passive

 
  1. <!-- Prevent click events from continuing to propagate -->
  2. <a @="doThis"></a>
  3. <!-- Submit event no longer reloads the page -->
  4. <form @="onSubmit"></form>
  5. <!-- Modifiers can be concatenated -->
  6. <a @="doThat"></a>
  7. <!-- Only modifiers -->
  8. <form @></form>
  9. <!-- Use event capture mode when adding event listeners -->
  10. <!-- That is, the events triggered by the internal element are processed here first, and then handed over to the internal element for processing -->
  11. <div @="doThis">...</div>
  12. <!-- The processing function is triggered only when it is the current element itself -->
  13. <!-- i.e. events are not triggered from internal elements -->
  14. <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.

 
  1. <!-- The click event will only be triggered once -->
  2. <a @="doThis"></a>

Unlike other modifiers that can only work on native DOM events,.onceModifiers 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.passiveModifier.

 
  1. <!-- The default behavior of the scroll event (i.e. the scrolling behavior) will be triggered immediately -->
  2. <!-- without waiting for `onScroll` to complete -->
  3. <!-- This includes the case where `()` -->
  4. <div @="onScroll">...</div>

this.passiveModifiers can especially improve mobileperformance

TIP

Don't put it.passiveand.preventUse together because.preventIt will be ignored, and the browser may show you a warning. Please remember,.passiveWill tell the browser youIn no moodThe default behavior of blocking events.

#Key modifier

ListeningKeyboard eventsWhen we often need to check detailed keys. Vue allowsv-onor@Add key modifiers when listening for keyboard events:

 
  1. <!-- `()` is called only if `key` is `Enter` -->
  2. <input @="submit" />

You can directlyAny exposed valid key name is converted to kebab-case as a modifier.

 
  1. <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:

 
  1. <!-- Alt + Enter -->
  2. <input @="clear" />
  3. <!-- Ctrl + Click -->
  4. <div @="doSomething">Do something</div>

TIP

Please note that the modifier key is different from the regular key, andkeyupWhen events are used together, the modifier key must be pressed when the event is triggered. In other words, only press and holdctrlIn the case of  release other buttons to trigger. And just releasectrlEvents will not be triggered.

#.exactModifier

.exactModifiers allow you to control events triggered by precise combinations of system modifiers.

 
  1. <!-- Triggers even when Alt or Shift is pressed together -->
  2. <button @="onClick">A</button>
  3. <!-- There is and only triggers when Ctrl is pressed -->
  4. <button @="onCtrlClick">A</button>
  5. <!-- Triggered only when no system modifier is pressed -->
  6. <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-onor@There are several benefits:

  1. Scan the HTML template to easily locate the corresponding methods in JavaScript code.
  2. 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.
  3. When a ViewModel is destroyed, all event processors are automatically deleted. You don't have to worry about how to clean them up.