event handling


Directory


##Listening events

You can use

v- The on
directive listens for DOM events and runs some JavaScript code when triggered.

Example:

<div id="example-1">
  <button v-on:click="counter += 1">Add 1</button>
  <p>The button above has been clicked {{ counter }} times.</p>
</div>
var example1 = new Vue({
  el: '#example-1',
  data: {
    counter: 0
  }
})

Result:

2.gif


#Event handling method

#However, many event processing logic will be more complex, so it is not feasible to write JavaScript code directly in the v-on

directive. Therefore
v-on

can also receive a method name that needs to be called. Example:

<div id="example-2">
  <!-- `greet` 是在下面定义的方法名 -->
  <button v-on:click="greet">Greet</button>
</div>
var example2 = new Vue({
  el: '#example-2',
  data: {
    name: 'Vue.js'
  },
  // 在 `methods` 对象中定义方法
  methods: {
    greet: function (event) {
      // `this` 在方法里指向当前 Vue 实例
      alert('Hello ' + this.name + '!')
      // `event` 是原生 DOM 事件
      if (event) {
        alert(event.target.tagName)
      }
    }
  }
})
// 也可以用 JavaScript 直接调用方法
example2.greet() // => 'Hello Vue.js!'

Result:

1.gif

## Methods in inline processors

In addition to being directly bound to a method, methods can also be called in inline JavaScript statements:
<div id="example-3">
  <button v-on:click="say('hi')">Say hi</button>
  <button v-on:click="say('what')">Say what</button>
</div>
new Vue({
  el: '#example-3',
  methods: {
    say: function (message) {
      alert(message)
    }
  }
})
Result:


3.gif Sometimes it is also necessary to access raw DOM events in the inline statement handler. You can use the special variable

$event

to pass it into the method:

<button v-on:click="warn('Form cannot be submitted yet.', $event)">
  Submit
</button>
// ...
methods: {
  warn: function (message, event) {
    // 现在我们可以访问原生事件对象
    if (event) event.preventDefault()
    alert(message)
  }
}

Event modifier

It is a very common requirement to call event.preventDefault() or

event.stopPropagation()
in an event handler. Although we can easily implement this in methods, it is better to have methods with pure data logic instead of dealing with DOM event details.

To solve this problem, Vue.js provides event modifier for v-on. As mentioned before, modifiers are represented by instruction suffixes starting with a dot.

  • .stop

  • ##.prevent

  • .capture

  • .self

  • .once

  • .passive

    ##
    <!-- 阻止单击事件继续传播 -->
    <a v-on:click.stop="doThis"></a>
    
    <!-- 提交事件不再重载页面 -->
    <form v-on:submit.prevent="onSubmit"></form>
    
    <!-- 修饰符可以串联 -->
    <a v-on:click.stop.prevent="doThat"></a>
    
    <!-- 只有修饰符 -->
    <form v-on:submit.prevent></form>
    
    <!-- 添加事件监听器时使用事件捕获模式 -->
    <!-- 即元素自身触发的事件先在此处理,然后才交由内部元素进行处理 -->
    <div v-on:click.capture="doThis">...</div>
    
    <!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
    <!-- 即事件不是从内部元素触发的 -->
    <div v-on:click.self="doThat">...</div>
When using modifiers, the order is important; accordingly Code will be generated in the same order. Therefore, using
v-on:click.prevent.self

will prevent all clicks, while v-on:click.self.prevent will only prevent the Click on the element itself.

2.1.4 Newly added

<!-- 点击事件将只会触发一次 -->
<a v-on:click.once="doThis"></a>

Unlike other modifiers that can only work on native DOM events,
.once

Modifiers can also be used on custom component events. If you haven't read the documentation on your components, don't worry now.

2.3.0 Newly added

Vue also corresponds to the
passive

option provided in addEventListener .passive modifier.

<!-- 滚动事件的默认行为 (即滚动行为) 将会立即触发 -->
<!-- 而不会等待 `onScroll` 完成  -->
<!-- 这其中包含 `event.preventDefault()` 的情况 -->
<div v-on:scroll.passive="onScroll">...</div>
This

.passive

modifier can especially improve mobile performance.

Do not use
.passive

with .prevent because .prevent will be ignored and the browser may Show you a warning. Remember, .passive tells the browser that you don't want to block the default behavior of the event.


##Key modifier

When listening for keyboard events, we often Need to check detailed keys. Vue allows

v-on
to add key modifiers when listening to keyboard events:

<!-- 只有在 `key` 是 `Enter` 时调用 `vm.submit()` -->
<input v-on:keyup.enter="submit">
You can directly expose

KeyboardEvent.key

Any valid keyname is converted to kebab-case as a modifier.

<input v-on:keyup.page-down="onPageDown">
In the above example, the handler function will only be called when $event.key

is equal to

PageDown.


Key code

keyCode
event usage

has been deprecated and may not be supported by the latest browsers. Using the

keyCode
feature is also allowed:

<input v-on:keyup.13="submit">
In order to support old browsers where necessary, Vue provides most commonly used keycodes Alias:
  • .enter

  • .tab

  • .delete (Captures "Delete" and "Backspace" keys)

  • .esc

  • .space

  • .up

  • ##.down

  • .left

  • .right

Some keys (

.esc and all arrow keys) have different key values ​​in IE9, if you want to support IE9, these built-in aliases should be preferred .

You can also customize the key modifier alias

through the global config.keyCodes object:

// 可以使用 `v-on:keyup.f1`
Vue.config.keyCodes.f1 = 112


System Modifier Key


2.1.0 New

You can use the following modifiers to Implement a listener for mouse or keyboard events that only fires when the corresponding key is pressed.

  • .ctrl

  • ##.alt

  • .shift

  • .meta

Note: On a Mac system keyboard, meta corresponds to the command key (?). On the Windows system keyboard meta corresponds to the Windows logo key (?). On Sun operating system keyboards, meta corresponds to the solid gem key (◆). On certain other keyboards, especially those of the MIT and Lisp machines, and their successors, such as the Knight keyboard and the space-cadet keyboard, meta is marked as "META". On the Symbolics keyboard, meta is marked as "META" or "Meta".

For example:
<!-- Alt + C -->
<input @keyup.alt.67="clear">

<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>

Please note that modifier keys are different from regular keys. When used together with the
keyup

event, the modifier key is modified when the event is triggered. The key must be pressed. In other words, keyup.ctrl can only be triggered by releasing other keys while holding down ctrl. And simply releasing ctrl will not trigger the event. If you want this behavior, use keyCode for ctrl instead: keyup.17.


##.exact Modifier2.5.0 New

.exact
modifiers allow you to control events triggered by an exact combination of system modifiers.

<!-- 即使 Alt 或 Shift 被一同按下时也会触发 -->
<button @click.ctrl="onClick">A</button>

<!-- 有且只有 Ctrl 被按下的时候才触发 -->
<button @click.ctrl.exact="onCtrlClick">A</button>

<!-- 没有任何系统修饰符被按下的时候才触发 -->
<button @click.exact="onClick">A</button>


Mouse button modifier

##2.2.0 New

.left
  • .right

  • .middle

These Modifiers restrict the handler function to respond only to specific mouse buttons.


Why listen for events in HTML?


You may notice this kind of event The listening approach goes against the longstanding tradition of separation of concerns. But don’t worry, because all Vue.js event handlers and expressions are strictly bound to the current view’s ViewModel, it won’t cause any maintenance difficulties. In fact, using v-on has several advantages:

1. You can easily locate the corresponding method in the JavaScript code by scanning the HTML template.

 2. Because you don’t need to manually bind events in JavaScript, your ViewModel code can be very pure logic, completely decoupled from the DOM, and easier to test.

 3. When a ViewModel is destroyed, all event handlers will be automatically deleted. You don’t have to worry about cleaning them.