Vuex:_this。$ store未定义

时间:2018-02-15 03:39:38

标签: vue.js vuex

将Vuex添加到我的项目后,我无法访问此。$ store存储在任何组件中。错误消息是

  

TypeError:_this。$ store is undefined

我已经看过一堆已经试图解决这个问题的问题,但据我所知,我做的一切都是正确的。有人可以帮忙吗?我使用vue-cli webpack作为我的项目基础

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"
  },
...

3 个答案:

答案 0 :(得分:5)

解决:

使用创建的胖箭头不正确,应为created: function() {...}

答案 1 :(得分:1)

使用箭头功能时,“ this”将不是您所期望的Vue实例,因为箭头功能已绑定到父上下文。相反,

    created() { //function body. "this" will be the Vue instance},
    mounted() {//function body. "this" will be the Vue instance},
    methods: { someFunc() {}, async someAsyncFunc {} }

答案 2 :(得分:0)

将商店从app.js移到/store/index.js后,我也遇到了这个问题

我不得不在提交中将state.store.myValue更改为store.myValue