LoginSignup
1
1

More than 3 years have passed since last update.

methodでよくない?coumputedとmethodの違いを調べてみた

Posted at

はじめに

この記事ではVue.js2を使っています。
初学者のため、至らない部分や間違い等あればご教授よろしくお願いします。
Vue.jsを勉強しているとcoumputedプロバティが出てきてあれ、これmethodプロバティでいいんじゃない?ってなったので違いはどこにあるのか調べてみました。

結論

coumputedプロバティは、依存関係にもとづきキャッシュされる
methodプロバティは、描写が変わるたびに実行される

動きを確認してみる

とは言っても、文字だけだと難しいという方は続きをご覧ください。

プログラムの仕様

coumputedプロバティとmethodプロバティの挙動を確認します。

・number が3以下の時に"3以下"を表す

・number が3以上の場合は"3より上"を表す

index.html

<!-- Vue.jsのインストール -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <p>{{ number }}</p>
  <button @click="number += 1">+1</button>

<!-- coumputed -->
  <p>coumputedプロパティ->{{ Coumputed }}</p>
<!-- method -->
  <p>methodプロパティ->{{ Method() }}</p>
</div>


new Vue({
 el: "#app",
   data: {
     number: 0,
     },
   //coumputedプロパティ
   computed: {
     Coumputed: function() {
       return this.number > 3 ? "3より上" : "3以下"
     }
   },
   //methodsプロパティ
   methods: {
     Method: function() {
       return this.number > 3 ? "3より上" : "3以下"
     }
   }
})

結果

結果は同じ挙動となりました。
methodプロパティでもcoumputedプロパティと同じ挙動となりました。
スクリーンショット 2020-11-08 12.02.04.png

ソースの追加

関数がいつ実行されているかを確認してみます。
<追加点>

・index.htmlにohternumberを追加

・console.logを追加

index.html

<!-- Vue.jsのインストール -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <p>{{ number }}</p>
  <button @click="number += 1">+1</button>
 <!-- 追加 -->
 <p>{{ othernumber }}</p>
  <button @click="othernumber += 1">+1</button>

<!-- coumputed -->
  <p>coumputedプロパティ->{{ Coumputed }}</p>
<!-- method -->
  <p>methodプロパティ->{{ Method() }}</p>
</div>


new Vue({
 el: "#app",
   data: {
     number: 0,
     //追記
     othernumber: 0,
     },
   //coumputedプロパティ
   computed: {
     Coumputed: function() {
       //追記
       console.log("Computed");
       return this.number > 3 ? "3より上" : "3以下"
     }
   },
   //methodsプロパティ
   methods: {
     Method: function() {
       //追記  
       console.log("Methods");
       return this.number > 3 ? "3より上" : "3以下"
     }
   }
})

結果

coumputedプロバティは、依存関係にもとづきキャッシュされ、methodプロバティは、依存関係にない場合でも描写が変わるたびに実行されていました。

numberを押した場合

スクリーンショット 2020-11-08 12.49.19.png

coumputedプロバティもmethodプロバティも挙動を確認できました。

othernumberを押した場合

スクリーンショット 2020-11-08 12.49.58.png
methodプロパティが実行されており、依存関係にない場合でも描写が変わるたびに実行されてることが分かりました。

最後に

coumputedプロバティ
インスタンスに持たせて参照できるようにしたいときに用いる
methodプロバティ
クリック時、マウスオーバー時等の何かアクションが起きた時に処理を行うような場合に用いることがいいようです。

参考記事
https://dev83.com/vue-computed-methods/

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