1
votes

I am trying to make simple Vuex app and here are my files:

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>

Also I'm using 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
    }
  ]
})

And after initializing the store in the main.js and injecting in the App.vue component the this.$store variable in App.vue is undefined; but at the same time in main.js all is okay.

Also trying to import the store from the App.vue (later I stored store in store/index.js) make new store, without changed state in main.js.

2

2 Answers

4
votes

Your console.log('app', this.$store) is outside of your export default {}

And in any case, the this.$store code should be placed inside any of the following:

computed() {}

mounted()

methods: {}

2
votes

At the point where you're attempting to access this.$store, this doesn't point to the Vue instance.

You can access the store in one of the life-cycle hooks for the Vue instance (e.g. created):

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