LoginSignup
1
0

More than 3 years have passed since last update.

【備忘録】Vue:methodsとcomputedの違い

Last updated at Posted at 2021-01-17

Vueの動作オプションであるmethodsとcomputedの違いに関して

new Vue({
  computed: {
      ...
  },
  methods: {
      ...
  }
})

参考

これからはじめるVue.js実践入門

内容

下記のようなプログラムで違いを説明。
【プログラム内容】
- 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();
        }
    },
});

↓ ブラウザで表示した実際の画
image.png

共通点

ページ遷移した時は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も実行される。

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