LoginSignup
1
1

More than 1 year has passed since last update.

【Vue.js】computedとmethodsの違い

Last updated at Posted at 2021-05-06

はじめに

仕事で使う事になったので1からVue.jsについて学んだ。ちゃんと覚えておかないとまずそうな事を備忘録として1つ1つ残しておく。

computedとmethodsの違い

見た目の挙動は同じだが、動きには大きな違いがあるのでちゃんと使い分けないといけないのがcomputedmethods
それぞれについてまとめると以下の表のようになる。
あるべきとしては関係のある部分が更新された時だけ変更されるべきなのでcomputedを用いるのが正解。

# 説明 実行タイミング
computed 動的なプロパティを定義できるプロパティ。
プロパティなので必ずreturnが必要。
依存関係(参照先の値)が更新された時だけ実行。
method メソッドを定義できるプロパティ。 DOMが再描画されたときに毎回実行。

以下の動画のようにconsole.log()を出すとその違いが良く分かる。
ezgif.com-gif-maker.gif
動画のソースコードは以下。

sample.html
<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <p>{{ counter }}</p>
        <button @click="counter += 1">+1</button>
        <p>{{ anotherCounter }}</p>
        <button @click="anotherCounter += 1">他の+1</button>
        <p>{{ lessThanThreeComputed }}</p>
        <p>{{ lessThanThreeMethod() }}</p>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                counter: 0,
                anotherCounter: 0
            },
            computed: {
                lessThanThreeComputed: function () {
                    console.log('computed');
                    return this.counter > 3 ? '3より上' : '3以下';
                }
            },
            methods: {
                lessThanThreeMethod: function () {
                    console.log('methods');
                    return this.counter > 3 ? '3より上' : '3以下';
                }
            }
        })
    </script>
</body>

</html>

※ちなみにdataプロパティは動的なものは表現できず初期値を定義するだけに使われるので以下のような事はできない

data-prop.js
new Vue({
  el: '#app',
  data: {
    counter: 0
    // lessThanThree: this.counter <-できない
    // lessThanThree: counter > 3 ? '3より上' : '3以下' <-できない
  }
})

Vue.jsの勉強メモ一覧記事へのリンク

Vue.jsについて勉強した際に書いた勉強メモ記事のリンクを集約した記事。

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