<div id="example-2"> <!-- `greet` is the name of a method defined below --> <button v-on:click="greet">Greet</button> </div>
var example2 = new Vue({ el: '#example-2', data: { name: 'Vue.js' }, // define methods under the `methods` object methods: { greet: function (event) { // `this` inside methods points 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 example2.greet() // -> 'Hello Vue.js!'
<!-- the click event's propagation will be stopped --> <a v-on:click.stop="doThis"></a> <!-- the submit event will no longer reload the page --> <form v-on:submit.prevent="onSubmit"></form> <!-- modifiers can be chained --> <a v-on:click.stop.prevent="doThat"></a> <!-- just the modifier --> <form v-on:submit.prevent></form> <!-- use capture mode when adding the event listener --> <div v-on:click.capture="doThis">...</div> <!-- only trigger handler if event.target is the element itself --> <!-- i.e. not from a child element --> <div v-on:click.self="doThat">...</div>
Key修饰符
当监听键盘事件时,我们需要查看key code,Vue也为v-on提供了键盘事件的修饰符:
1 2
<!-- only call vm.submit() when the keyCode is 13 --> <input v-on:keyup.13="submit">
技术所有的key code是很难的,为此Vue提供了常用key code的别名:
1 2 3 4
<!-- same as above --> <input v-on:keyup.enter="submit"> <!-- also works for shorthand --> <input @keyup.enter="submit">