I use VueJS in combination with vuex and vue-router . I have a vuex module that creates a mutation in its repository and tries to use this to determine if the user is authenticated.
This is what my code looks like in the relevant part.
main.js
import Vue from 'vue' import App from './App.vue' import store from './store' import router from './router' router.beforeEach((to, from, next) => { console.log(router.app) // prints a Vue$2 object console.log(router.app.$store) // undefined console.log(store.getters.isAuthenticated) // false ... } const app = new Vue({ store, router, ...App }) app.$mount('#app')
/store/index.js
import Vue from 'vue' import Vuex from 'vuex' import core from './modules/core' Vue.use(Vuex) const store = new Vuex.Store({ modules: { core: core } }) export default store
/store/modules/core.js
import * as types from '../types' import api from '../../api' import router from '../../router' const state = { token: null, user: null, authenticated: false } const mutations = { [types.LOGIN_SUCCESS] (state, payload) { console.log('mutate') state.token = payload.token state.user = payload.user state.authenticated = true router.go('/') } } const getters = { isAuthenticated: state => { return state.authenticated } } const actions = { [types.LOGIN] (context, payload) { api.getToken(payload).then(response => { context.commit(types.LOGIN_SUCCESS, response) }) } } export default { state, mutations, actions, getters }
When I go through my logic to trigger the LOGIN action, I see that the mutation is done correctly, and when I use the Chrome extension to view the vuex state for my core module, the state for user > and authenticated were mutated correctly.
Question
It seems that this module simply was not loaded by the time the router started in the .beforeEach loop. It's true?
If so, what are some other suggestions on how to deal with this situation? If not, what am I doing wrong?
The brewmaster
source share