環境
- 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: {…},
とコンポーネント自身が取得できているのが確認できた。