Vue.js Event Handlers

Event listening can use the v-on directive:

v-on

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

Try it Yourself »

Usually, we need to use a method to call a JavaScript method.

v-on can accept a defined method to invoke.

v-on

<div id="app"> <!--`greet` is the name of the method defined below--> <button v-on:click="greet">Greet</button> </div> <script>var app = new Vue({ el: '#app', data: { name: 'Vue.js' }, // Define methods in the `methods` object methods: { greet: function (event) { // `this` in a method refers to the current Vue instance alert('Hello ' + this.name + '!') // `event` is the native DOM event if (event) { alert(event.target.tagName) } } } }) // You can also call the method directly using JavaScript app.greet() // -> 'Hello Vue.js!'</script>

Try it Yourself »

In addition to directly binding to a method, you can also use inline JavaScript statements:

v-on

<div id="app"> <button v-on:click="say('hi')">Say hi</button> <button v-on:click="say('what')">Say what</button> </div> <script> new Vue({ el: '#app', methods: { say: function (message) { alert(message) } } }) </script>

Try it Yourself »

Event Modifiers

Vue.js provides event modifiers for v-on to handle DOM event details, such as event.preventDefault() or event.stopPropagation().

Vue.js uses the dot.as the directive suffix to invoke modifiers.

  • .stop- Prevent bubbling
  • .prevent- Prevent default event
  • .capture- Prevent capture
  • .self- Only listen for events that trigger on this element
  • .once- Trigger only once
  • .left- Left-click event
  • .right- Right-click event
  • .middle- Middle mouse wheel event
<!-- 阻止单击事件冒泡 -->
<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>
<!-- 只当事件在该元素本身(而不是子元素)触发时触发回调 -->
<div v-on:click.self="doThat">...</div>

<!-- click 事件只能点击一次,2.1.4版本新增 -->
<a v-on:click.once="doThis"></a>

Key Modifiers

Vue allows adding key modifiers to v-on when listening to keyboard events:

<!-- 只有在 keyCode 是 13 时调用 vm.submit() -->
<input v-on:keyup.13="submit">

Remembering all keyCodes is difficult, so Vue provides aliases for the most commonly used keys:

<!-- 同上 -->
<input v-on:keyup.enter="submit">
<!-- 缩写语法 -->
<input @keyup.enter="submit">

All key aliases:

  • .enter
  • .tab
  • .delete(Captures the 'Delete' and 'Backspace' keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right
  • .ctrl
  • .alt
  • .shift
  • .meta

Example

<p><!-- Alt + C -->
<input @keyup.alt.67="clear">
<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>
Other Extensions