【问题标题】:Vuex this.$store is undefined in child componentVuex this.$store 在子组件中未定义
【发布时间】:2018-08-01 08:33:35
【问题描述】:

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

ma​​in.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
    }
  ]
})

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

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

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

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

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

    computed() {}

    mounted()

    methods: {}

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2019-12-29
        • 2018-11-23
        • 2020-03-03
        • 2019-10-01
        • 2019-04-05
        • 2018-07-25
        • 1970-01-01
        • 2019-11-04
        • 2023-03-18
        相关资源
        最近更新 更多