Vue.js event handler

Event listeners can use the v-on command:


<div id=" app"> <button v-on:click="counter += 1">Add 1</button> <p>This button was clicked {{ counter }} times. </p> </div> <script> New vue({ El: '#app', Data: { Counter: 0 } }) </script>

In general, we need to use a method to call a JavaScript method.

v-on can receive a defined method to call.


<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` refers to the current Vue instance in the method Alert('Hello ' + this.name + '!') // `event` is a native DOM event If (event) { Alert(event.target.tagName) } } } }) // can also call methods directly using JavaScript App.greet() // -> 'Hello Vue.js!' </script>

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


<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>

Event modifier

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

Vue.js invokes modifiers with an instruction suffix represented by a dot (.).

  • .stop
  • .prevent
  • .capture
  • .self
  • .once
<!-- Block click event bubbling -->
<a v-on:click.stop="doThis"></a>
<!-- Submit events no longer reload pages -->
<form v-on:submit.prevent="onSubmit"></form>
<!-- modifiers can be concatenated -->
<a v-on:click.stop.prevent ="doThat"></a>
<!-- Only modifiers -->
<form v-on:submit.prevent></form>
<!-- Use event capture mode when adding event listeners -->
<div v-on:click.capture="doThis">...</div>
<!-- only triggers a callback when the event fires on the element itself (rather than a child element) -->
<div v-on:click.self="doThat">...</div>

<!-- click event can only be clicked once, added in version 2.1.4 -->
<a v-on:click.once=" doThis"></a>

Key modifiers

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

<!-- Call vm.submit() -->
<input v-on:keyup.13="submit"> 

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

<!-- Ibid -->
<input v-on:keyup.enter="submit">
<!-- Abbreviation Syntax -->
<input @keyup.enter="submit">

All key aliases:

  • .enter
  • .tab
  • .delete (capture the "delete" and "backspace" keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right
  • .ctrl
  • .alt
  • .shift
  • .meta


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

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.