LoginSignup
23
11

More than 5 years have passed since last update.

Vue.jsでthis.$storeにアクセスできない書き方

Last updated at Posted at 2019-01-22

環境

  • Vue.2.5.1
  • Vuex 3.0.1

this.$store→undefinedエラー

this.$store.getters['auth']

のように $store を使おうとすると下記のエラーが出た。

Error in created hook: "TypeError: Cannot read property '$store' of undefined"

原因

イキってアロー関数を使ったから。

created: () => {
  this.$store.getters['auth'] // "TypeError: Cannot read property '$store' of undefined"
  console.log(this.$store) // "TypeError: Cannot read property '$store' of undefined"
  console.log(this)  // undefined
}

そもそも this がundefined。

アロー関数式 は、その名のとおり矢印を使って記述し、function 式より短い構文で同様な内容を記述することができます。なおthis, arguments, super, new.target を束縛しません。

つまり「thisが空ということが有り得る」という捉え方で良いのかな。

試しに下記のようなオブジェクトで実験してみた。

const obj = {
  func1: function() {
    console.log(this); // {func1: f, func2: f, func3: f}
  },
  func2() {
    console.log(this); // {func1: f, func2: f, func3: f}
  },
  func3: () => {
    console.log(this); // undefined
  }
};

func1とfunc2ではthisでオブジェクト自身が取得できている。

結論

created: function() {
  console.log(this)
}

もしくは

created() {
  console.log(this)
}

のように書くと VueComponent {_uid: 7, _isVue: true, $options: {…}, とコンポーネント自身が取得できているのが確認できた。

23
11
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
23
11