Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

vue.js - Vuex: _this.$store is undefined

After adding Vuex to my project I am unable to access this.$store in any components. The error message is

TypeError: _this.$store is undefined

I have looked at a bunch of questions already trying to solve this but as far as I can tell I'm doing everything right. Can anyone help? I am using the vue-cli webpack as my project base

main.js:

import Vue from 'vue';
import resource from 'vue-resource';
import router from './router';
import store from './store/index.js';

import App from './App';
import Home from './components/Home';
import NavButton from './components/atoms/NavButton';

Vue.use(resource);
Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App, Home, NavButton },
  template: '<App/>'
})

/store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const state = {
    isWriting: false,
    isLoggedIn: false,
}

const getters = {
    isWriting: state => {
        return state.isWriting;
    }
}

export default new Vuex.Store({
    state,
    getters,
});

App.vue

...
import NavBar from '@/components/organisms/NavBar';
export default {
  name: 'App',
  components: { NavBar },
  created: () => {
    console.log(this.$store.state.isLoggedIn); // THIS LINE
  }
}
...

package.json

...
"dependencies": {
    "vue": "^2.5.2",
    "vue-resource": "^1.3.6",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1"
  },
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

SOLVED:

Using fat arrow on created is not correct, should be created: function() {...}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...