Vueの動作オプションであるmethodsとcomputedの違いに関して
new Vue({
computed: {
...
},
methods: {
...
}
})
参考
内容
下記のようなプログラムで違いを説明。
【プログラム内容】
- computedで乱数を表示
- methodsで乱数を表示
- クリックで現在日時を表示
sample.html
...
<body>
<div id="app">
<form>
<input type="button" value="click" v-on:click="onclick" />
</form>
<div>computed: {{randomc}}</div>
<div>methods: {{randomm()}}</div>
<div>daytime: {{current}}</div>
</div>
...
</body>
sample.s
new Vue({
el: '#app',
data: {
current: new Date().toLocaleString()
},
computed: {
randomc: function() {
return Math.random();
}
},
methods: {
onclick: function(){
this.current = new Date().toLocaleString();
},
randomm: function() {
return Math.random();
}
},
});
共通点
ページ遷移した時はcomputedとmethodsのどちらも実行される。
異なる点
1) methodsはhtml上で使うときに引数を持てる。computedは引数を持てない。
<div>methods: {{randomm(ここに引数を入れられる)}}</div>
2) methodsはページが再描画されるたびに実行される。一方で、computedはページに遷移した初回のみ呼び出したときと、依存したプロパティが更新されたときのみ実行される。
つまり、今回の例だと「クリック」ボタンをクリックしたときに、現在時間が再描画されるので、その際にmethodsの乱数生成は実行されて、computedの乱数生成は実行されない。
ただし、
computed: {
randomc: function() {
console.log(this.current);
return Math.random();
}
},
のように現在時刻を参照すると、computedも実行される。