1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nuxt.jsでthis.oooが呼べなかった

1
Posted at

背景

Nuxtをいじっていて、特定のメソッドでthis.oooが呼べない問題に遭遇して、しばらく原因がわからず悩んでいた。

結論

以下のようにアロー関数で記述していたが、

methods: {
            funcName: () => {
                 // ~ logic ~
            },
            funcName2: () => {...

こうしないと駄目だった。

methods: {
            funcName: function() {
                 // ~ logic ~
            },
            funcName2: function() {...

原因

アロー関数はthisの値を束縛しない(レキシカルに束縛する)ので、Vueインスタンス内のメソッドにアクセスできないことが原因でした。

※アロー関数
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Functions/Arrow_functions

補足

ちゃんとVueのドキュメントなどに書いてある。

メソッド(例 plus: () => this.a++) を定義するためにアロー関数を使用すべきではないことに注意してください。アロー関数は、this が期待する Vue インスタンスではなく、this.a が undefined になるため、親コンテキストに束縛できないことが理由です。

ちゃんとドキュメント読もうな俺^^

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?