Vue.js- methods and events

Learning notes:Methods and Events

Methods and Events

@click can call a method name without parentheses(), if the method has parameters, the native event object will beeventIncoming.

This design of monitoring events on HTML elements seems to tightly couple DOM and JavaScript, which violates the principle of separation, but in fact it is just the opposite. Because you can know which method is called through HTML, decoupling logic from DOM, which is easy to maintain.

Most importantly, whenviewModelWhen destroying, all the event handlers will be destroyed automatically and need not be handled by themselves.

Vue provides a special variable$eventFor accessing native DOM events.

<div id="app">
    <a href="" @click="handleClick('禁止打开',$event)">打开链接</a>


Vue supports the following modifiers:

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

The specific usage is as follows:

Modifier function Use examples
Prevent click event bubbling <a @click.stop="handle"></a>
Submit events no longer reload pages <form @submit.prevent="handle"></form>
Modifiers can be concatenated <a @click.stop.prevent="handle"></a>
Only modifiers <form @submit.prevent></form>
Use event capture mode when adding event listeners <div @click.capture="handle">...</div>
Callbacks are only executed when the event triggers on the element itself (not a child element) <div @click.self="handle">...</div>
Triggered only once, the component is also applicable. <div @click.once="handle">...</div>

You can also use key modifiers when listening for keyboard events on form elements.

Modifier function Use examples
Only inkeyCodeYes13Called whenvm.submit() <input @keyup.13="submit">

In addition to the specific onekeyCodeIn addition, Vue also provides some shortcut names:

  • .enter
  • .tab
  • .delete(Replenishment “Delete” and “Backspace” Keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

These key modifiers can also be used in combination or with a mouse:

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