繁体   English   中英

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/>'
})

应用程序.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中初始化 store 并注入App.vue组件后,App.vue 中的this.$store变量未定义; 但同时在 main.js 中一切正常。

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

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

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

computed() {}

mounted()

methods: {}

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

您可以在 Vue 实例的生命周期钩子之一中访问存储(例如created ):

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

暂无
暂无

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

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