首页 文章

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

提问于
浏览
1

我正在尝试制作简单的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 组件后,App.vue中的 this.$store 变量未定义;但是在main.js的同时一切都还可以 .

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

2 回答

  • 1

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

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

    computed: {}

    mounted ()

    methods: {}

  • 2

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

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

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

相关问题