Vuex this。$ store在子组件

时间:2018-02-21 16:55:15

标签: vue.js vuex

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

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

2 个答案:

答案 0 :(得分:4)

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

之内

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

computed() {}

mounted()

methods: {}

答案 1 :(得分:2)

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

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

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