开发者问题收集

Vuex:_this.$store 未定义

2018-02-15
8265

将 Vuex 添加到我的项目后,我无法在任何组件中访问 this.$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个回答

已解决:

在 created 上使用粗箭头是不正确的,应该是 created: function() {...

Jared Jones
2018-02-15

使用箭头函数时,“this”不会像您预期的那样是 Vue 实例,因为箭头函数绑定到父上下文。相反,

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

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

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

Dazzle
2018-07-29