SoFunction
Updated on 2025-04-06

Detailed explanation of the binding example of Vue event handling function

text

In JS, "events" do not need to be bound. The browser comes with many events, and each event can be bound to the "processor (processing function)".

Event ==> User behavior ==> Event triggering the browser ==> Execute the corresponding event handling function

We usually passaddEventListenetMethod to bind the event to the processing function:

("click", function () {
  // do...
}, flase);

It should be noted thataddEventListenetIt's just that the "binding" event handler function is not "execution"! The processing function will only be executed when the corresponding event is triggered.

In some cases, we need to separate the processing functions and need to change themthisexecution, this is because of the event handler functionthisPointing to the element itself means we cannot use it.callTo changethispointing, because.callThe method will execute the function immediately!

// This will cause the test to be executed immediately!("click", (this), flase);
// You can use the .bind method to point to this with confidence, because bind will not be executed immediately("click", (this), flase);

Vue's event handling binding

comeVueVueProvidedv-onDirectives allow developers to bind event handling functions to elements, such as:

<div v-on:click="methodName"></div>
<!-- Or use @click right v-on Abbreviation -->
<div @click="handler"></div>

v-onThe value ofJSexpression:

<button @click="count += 1">Add</button>

This is not recommended, the logic should be put intomethodsProcessed inside.

v-onThe value can also be a method event handler:

 <button @click="onClickAdd">Add</button>

@clickAccepts a method name or a call to a method.

When binding the event handler function through the method name, we can pass parameters to the method:

<div>
  <h1>{{ count }}</h1>
  <button @click="onClickAdd(2)">Add</button>
  <button @click="onClickMinus(2, $event)">Minus</button>
</div>

The above code,buttonBoundedonClickAddandonClickMinusThe function will not be executed immediately after processing, but will be executed only after the event is triggered. This will start with what we said.addEventListenetIt's the same!

andonClickAddandonClickMinusThe brackets are for the convenience of passing parameters we want to pass inmethdosProcessing in.

Here is a special parameter$event, this property isVueAn internal encapsulation attribute that represents the event object that triggers the event.

const app = {
  template: `<button @click="onClickMinus(2, $event)">Minus</button>`,
  data(){
    return {
      count: 0
    }
  }
  methods:{
    onClickMinus(num, e){
      (e);
       += num;
    }
  }
}

v-onDirectives can also bind multiple event handlers at the same time, for example:

<div>
  <h1>{{ count }}</h1>
  <button @click="onClickAdd(),setLog()">Add</button>
  <button @click="onClickMinus">Minus</button>
</div>

Just use it between the two methods,By separating, two event handling functions can be bound at the same time.

Event modifier

We may call when processing events()or()It's very common.VueA set of "modifiers" is provided to help us complete these events. The purpose of this is to allow developers to focus more on data logic without having to deal with it.DOMDetails of the event.

The modifier is a directive suffix represented by ., which contains the following:

  • .stop: Stop the event from bubbles.
  • .prevent: The default behavior of blocking events.
  • .self:whenThe event handler will be triggered only when it is the element itself.
  • .capture: Use event capture.
  • .once: After the event is called once, the listener will be automatically removed.
  • .passive:Modifier is generally used for touch events listeners and can be usedImprove the scrolling performance of mobile devices

⚠️ Attention

Cannot be used at the same time.passiveand.prevent,because.passiveThe default behavior of the browser that you do not want to block events has been shown.
If you do,.preventWill be ignored and the browser will throw a warning.

&lt;!-- Clicking the event will stop passing --&gt;
&lt;a @="doThis"&gt;&lt;/a&gt;

&lt;!-- Submit event will no longer reload the page --&gt;
&lt;form @="onSubmit"&gt;&lt;/form&gt;

&lt;!-- Modifications can be written in chain --&gt;
&lt;a @="doThat"&gt;&lt;/a&gt;

&lt;!-- There are also modifiers --&gt;
&lt;form @&gt;&lt;/form&gt;

&lt;!-- Only when  The event handler will be triggered when it is the element itself. --&gt;
&lt;!-- For example:Event handlers do not come from child elements --&gt;
&lt;div @="doThat"&gt;...&lt;/div&gt;

Pay attention to the order of call when using modifiers, because the relevant code is generated in the same order. Therefore use@will block the default behavior of all click events of the element and its children, and@This will only prevent the default behavior of click events to the element itself.

Key modifier

We may need to passTo determine the user triggered keys,VueAllowed inv-onor@Add a key modifier when listening for key events, for example:

&lt;!-- Only in `key` for `Enter` Called on time `submit` --&gt;
&lt;input @="submit" /&gt;

You can use it directlyThe exposed key name is used as a modifier, but needs to be converted to the kebab-case form.

<input @-down="onPageDown" />

VueAlias ​​are provided for some commonly used keys:

  • .enter
  • .tab
  • .delete(capture"Delete"and"Backspace"Two buttons)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

You can use the following system key modifiers to trigger the mouse or keyboard event listener, which will only be triggered when the key is pressed.

  • .ctrl
  • .alt
  • .shift
  • .meta

For example:

&lt;!-- Alt + Enter --&gt;
&lt;input @="clear" /&gt;

&lt;!-- Ctrl + Click --&gt;
&lt;div @="doSomething"&gt;Do something&lt;/div&gt;

Please note that the system key modifier is different from the regular key. andkeyupWhen events are used together, the key must be pressed when the event is emitted.
in other words,It will only hold it when you still hold itctrlBut it is triggered when another key is released. If you let go alonectrlThe key will not fire.

.exactModifiers allow control of the system key modifiers required to trigger an event.

&lt;!-- When pressed Ctrl hour,即使同hour按下 Alt or Shift It will also trigger --&gt;
&lt;button @="onClick"&gt;A&lt;/button&gt;

&lt;!-- 仅When pressed Ctrl 且未按任何其他键hour才会触发 --&gt;
&lt;button @="onCtrlClick"&gt;A&lt;/button&gt;

&lt;!-- 仅当没有按下任何系统按键hour触发 --&gt;
&lt;button @="onClick"&gt;A&lt;/button&gt;

You can use the following mouse button modifiers to trigger the mouse event listener:

  • .left
  • .right
  • .middle

These modifiers limit the handler to events triggered by a specific mouse button.

Why does Vue listen for events in HTML?

We foundVueYestemplateThe direct binding of events in the event violates the concept of "separation of concerns". But don't worry,VueStrictly bind event processing methods and expressions to the current viewViewModelHe will not cause any maintenance difficulties.
When we usev-onThere are several benefits to binding event processing on view:

1. Scan theHTMLTemplate can be easily positionedJavaScriptThe corresponding method inside.

2. No need to be thereJavaScriptManually bind events to yoursViewModelCode can be non-pure logic, andDOMCompletely decoction, easier to test.

3. Be aViewModelWhen destroyed, all event processors will be automatically deleted. You need to worry about how to clean them up.

The above is a detailed explanation of the binding example of Vue event handling function. For more information about binding of Vue event handling function, please pay attention to my other related articles!