カタバミさんのプログラミングノート

日曜プログラマーがプログラミング関係のメモを記録するブログです。

Vue.jsのmethodsやcomputedにおける関数式の種類とthis

Vue.jsのcomputedでアロー関数*1を使ってthisで混乱したので覚え書きとして。結論は以下の通りです。

  1. Vue.jsのmethodsやcomputedでは匿名関数*2を使った方が素直
  2. アロー関数におけるthisの挙動は仕様

thisの仕様については詳細に調べていませんが、サンプルコードの結果からアロー関数と匿名関数では次表の違いがあります。methodsやcomputedで扱いたいthisの実体は基本的にVueなので、匿名関数を使った方が素直に扱えるかと思います。

関数式 thisの型
アロー関数 Window
匿名関数 Vue

サンプルコード

<html lang="ja">
    <head>
        <meta charset="utf-8">
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title></title>
    </head>
    <body>
        <div id="app1">
            <p>{{s1}}</p><!-- ABCDE -->
            <p>{{s2}}</p><!-- undefined2 Window -->
            <p>{{s3}}</p><!-- ABCDE3 Vue -->
        </div>
        <script>
            var app1 = new Vue({
                el: "#app1",
                data: {
                    s1: "ABCDE"
                },
                computed: {
                    s2: () => this.s1 + "2 " + this.constructor.name,
                    s3: function() {
                        return this.s1 + "3 " + this.constructor.name;
                    }
                }
            });
        </script>
    </body>
</html>

computedのs2とs3はそれぞれラムダ関数と匿名関数です。ラムダ関数s2ではthisの実体がWindowグローバルオブジェクトなのでthis.s1がundefinedとなりますが、匿名関数s3ではthisの実体がVueインスタンスなのでthis.s1はdataのs1の値です。

参考 jp.vuejs.org developer.mozilla.org

*1:Arrow function、アロー関数式

*2:無名関数、function式