Vuex this.$store 在子组件中未定义

Vuex this.$store is undefined in child component

我正在尝试制作简单的 Vuex 应用程序,这是我的文件:

main.js

/* eslint-disable no-unused-vars */
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import router from './router'
import BootstrapVue from 'bootstrap-vue'

// TODO make it work with css-loader, dunno why it's not working at my environment
import '../node_modules/bootstrap/dist/css/bootstrap.css'
import '../node_modules/bootstrap-vue/dist/bootstrap-vue.css'

Vue.use(BootstrapVue)

Vue.config.productionTip = false

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    isLogged: false
  },
  mutations: {
    logIn (state) {
      state.isLogged = true
    },
    logOut (state) {
      state.isLogged = false
    }
  }
})

store.commit('logIn')
console.log('main', store.state.isLogged)

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

App.vue

<template>
  <b-container>
    <b-row align-h="center">
      <b-col cols="4">
        <div id="app">
          <router-view/>
        </div>
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
// import store from './store'
// store.commit('logOut')
console.log('app', this.$store)
export default {
  // name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

我也在使用 vue-router:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Login from '@/components/Login'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    }
  ]
})

并且在 main.js 中初始化存储并在 App.vue 组件中注入 this.$store App.vue 中的变量未定义;但同时 main.js 一切正常。

还尝试从 App.vue 导入商店(后来我将商店存储在 store/index.js 中)创建新商店,而不更改 main.js.[=13= 中的状态]

你的 console.log('app', this.$store) 在你的 export default {}

之外

并且在任何情况下,this.$store 代码都应放在以下任何内容中:

computed() {}

mounted()

methods: {}

在您尝试访问 this.$store 时,this 并未指向 Vue 实例。

您可以在 Vue 实例的 life-cycle hooks 之一中访问商店(例如 created):

created() {
  console.log(this.$store);
}