繁体   English   中英

Vuex:_this。$ store未定义

[英]Vuex: _this.$store is undefined

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

解决了:

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM