LoginSignup
4
1

More than 3 years have passed since last update.

Vue.jsにおけるcomputedとmethodsの違い

Last updated at Posted at 2019-10-06

computed(算出プロパティ)とは

「算出プロパティ」とは任意に処理を含めることのできるデータのことです。
Mustacheやディレクティブの値にはJavaScriptが使用できますが、やたらに式を書き込んでしまえばテンプレートの見通しが悪くなってしまいます。算出プロパティに書き換えることでテンプレートの可読性を保つことができます。
引用元:基礎から学ぶ Vue.js p120

methodsとは

methodsは、このアプリケーションで使用するメソッドです。コードを管理しやすくするために処理を分けたり、イベントハンドラなど細かな実装を担当します。

computedとmethodsの挙動の比較

挙動の違いをコンソールで確認

「Increase」ボタンと「Increase Second」ボタンを押した際の挙動の違いをコンソールで確認してみよう。


See the Pen
oNNNdLo
by さと (@sssa324542)
on CodePen.


「Increase Second」ボタンと「Increase」ボタンを押した結果

「Increase Second」ボタン(computed)

consoleには「computed」のみ表示される。

「Increase」ボタン(methods)

consoleには「computed」と「methods」の両方が表示される。

なぜなのか?

computedはmethodsと違いリアクティブな依存関係にもとづきキャッシュされるためである。

下記表に整理すると

クリックしたボタン コンソール
Increase computed&methods
Increase Second methods

となるIncreaseボタンを押してコンソールにcomputedとmethodsが表示されるのはもちろんcounterの値が変わるとcomputedとmethods両方とも影響あるからである。しかし、Increase Secondボタンを押した場合はsecondCounterの値が変化し、methodsのみコンソールに表示される。

Vue.js
new Vue({
 el:'#app',
 data:{
  counter:0,
  secondCounter:0
 }
 computed:{
  output:function(){
   console.log('computed');
   return this.counter>5?'Greater than 5':'Smaller than 5';
  }
 },
 methods:{
  result(){
   console.log('methods');
   return this.counter>5?'Greater than 5':'Smaller than 5';
  }
 }
}
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1