基礎からメモ: Vue.js CH2-p59 データの更新
v-on
ディレクティブを使って、ボタンクリックでデータを更新するサンプル。
[main05.js]
var app = new Vue({ el: '#app', data: { count: 0 }, methods: { increment: function(event) { let that = this; that.count += 1; } })
次のHTMLで、v-on:click="increment"
という形で、クリックするとVueインスタンスのmethods.increment
が呼び出されるて、データのcount
が+1される。
[index05.html]
<div id="app"> <!-- countプロパティを表示する --> <p>{{ count }}回クリックしたよ!</p> <!-- このボタンをクリックするとincrementメソッドが呼び出される --> <button v-on:click="increment">カウントを増やす</button> <pre>{{ $data }}</pre> </div>
Vueインスタンス側で、let that = this; that.count += 1
としている。インスタンスのメソッド内でのthis
はインスタンスそのものを指すので、this.count
はapp.count
を表している。ここではいったんthat
に代入して使っているがメソッド内でやってもこの程度の内容では意味は無い。
むしろインスタンスをapp
変数に代入しているので、メソッド内でもこれを使った方がわかりやすい。
methods: { increment: function(event){ app.count += 1; } }
Vueインスタンス内でのthis
setTimeout
の中でのthis
はWindow
オブジェクトを指すので、これは機能しない。
setTimeout(function() { this.count++ }, 100);
そこでthis
を変数に代入しておくと機能する。メソッド内でthis
を別の変数に代入しておくのは、こういう場合に活きてくる。
let vm = this; setTimeout(function() { vm.count++ }, 100);
setTimeout
の中だけの問題ならbind
で紐付ける方法もある。
setTimeout(function() { this.count++ }.bind(this), 100);
アロー関数は、Vueインスタンスを指すthis
にアクセスできる。
setTimeout(()=> { this.count++ }, 100);
インスタンス内の別のメソッドを介すると機能する。
methods: { increment: function(event){ setTimeout(this.count_p, 100); }, count_p: function() { this.count++; } }
同じコードでこのcount_p
メソッドをアロー関数にしてしまうと機能しない。アロー関数のメソッドのスコープはインスタンスの外側になる。
count_p: () => { this.count++; }
逆に短縮記法なら問題ない。
count_p() { this.count++; }