首页 文章

Vuex:_this . $ store未定义

提问于
浏览
1

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

TypeError:_this . $ store未定义

我已经看过一堆已经试图解决这个问题的问题,但据我所知,我做的一切都是正确的 . 有人可以帮忙吗?我使用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 回答

  • 1

    解决了:

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

  • 3

    当使用箭头函数时,“this”将不是您期望的Vue实例,因为箭头函数绑定到父上下文 . 代替,

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

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

    我必须在提交中将 state.store.myValue 更改为 store.myValue

相关问题