Methods and Event Handling
Methods and Event Handling
Method Handler
We can use the v-on
directive to listen to DOM events:
<div id="example"> <button v-on:click="greet">Greet</button> </div>
We are binding a click event listener to a method named greet
. Here’s how to define that method in our Vue instance:
var vm = new Vue({ el: '#example', data: { name: 'Vue.js' }, // define methods under the `methods` object methods: { greet: function (event) { // `this` inside methods point to the Vue instance alert('Hello ' + this.name + '!') // `event` is the native DOM event alert(event.target.tagName) } } }) // you can invoke methods in JavaScript too vm.greet() // -> 'Hello Vue.js!'
Test it yourself: