LoginSignup
7
6

More than 3 years have passed since last update.

【Vue.js】computedとmethodsの違いまとめ

Last updated at Posted at 2020-12-12

はじめに

UdemyのVue.js講座で学習していたところ、computedとmethodsの違いがよく分からなかったので、備忘のためにアウトプットしたいと思います。

computedとmethodsの違い

computedがリアクティブな依存関係が更新されたときにだけ再評価されるのに対し、methodsは再描画が起きると常に関数が実行されます。

methods computed
オブジェクト内での役割 メソッド プロパティ
処理結果のキャッシュ キャッシュされない キャッシュされる
テンプレートからの呼び出し方 {{ call() }} {{ call }}
getter, setter getterのみ定義できる getter, setter両方定義できる

実際の動き

以下はcomputedが実行されるとcomputed発火!、methodsが実行されるとmethods発火!がコンソールに出力される処理です。


See the Pen
abmBreG
by TokioTakamiya (@tktaka)
on CodePen.


methodsの場合

methodsは再描画の度に関数が実行されるため、computed実行時でもcomputed発火!とともにmethods発火!も表示されています。

Screen Recording 2020-12-12 at 12.49.43.mov.gif

computedの場合

一方、methodsの実行時はcomputed発火!は画面リロード時の1度しか表示されておらず、methods発火!のみ増加しています。
Screen Recording 2020-12-12 at 13.02.53.mov.gif

次回の記事では、computedとwatchの違いについて触れたいと思います。

参考

Vue.js : 算出プロパティとメソッド

7
6
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
7
6