イベントのサブスクライブとイベントハンドラの記述を行う場合は、v-on
を使用します。
例えば以下のように記述します。
<div id="app">
{{count}}<br>
<button v-on:click="increment">Increment</button>
</div>
new Vue({
el: '#app',
data: {
count: 0
},
// `methods` オブジェクトの下にメソッドを定義する
methods: {
increment: function () {
this.count++;
}
}
});
v-on:click
でクリック時のイベントハンドラを指定します。
イベントハンドラ increment
は methods
プロパティの下に定義します。this
で data
プロパティにアクセスできます。
引数の渡し方
引数も普通に渡せばいいだけです。
<div id="app">
{{count}}<br>
<button v-on:click="increment(2)">Increment</button>
</div>
new Vue({
el: '#app',
data: {
count: 0
},
// `methods` オブジェクトの下にメソッドを定義する
methods: {
increment: function (value) {
this.count += value;
}
}
});
イベント引数
引数なしのイベントハンドラに引数を1つ指定すると、イベント引数が渡されます。
<div id="app">
<button v-on:click="helloWorld">Hello World</button>
</div>
new Vue({
el: '#app',
// `methods` オブジェクトの下にメソッドを定義する
methods: {
helloWorld: function (event) {
alert('Hello World!')
// `event` は、ネイティブ DOM イベントです
if (event) {
alert(event.target.tagName)
}
}
}
});
引数ありのイベントハンドラでイベント引数を受け取る
引数ありのイベントハンドラでイベント引数を受け取りたい場合は、$event
を渡します。
<div id="app">
<button v-on:click="helloWorld('Taro', $event)">Hello World</button>
</div>
new Vue({
el: '#app',
// `methods` オブジェクトの下にメソッドを定義する
methods: {
helloWorld: function (name, event) {
alert(`Hello ${name}!`)
// `event` は、ネイティブ DOM イベントです
if (event) {
alert(event.target.tagName)
}
}
}
});