在beforeEach期间将vuex模块状态传递到vue-router

JavaScript Vue.js

飞云JinJin

2020-04-07

我将VueJS与vuex结合使用vue-router我有一个vuex对其存储进行更改模块,并试图使用该模块来确定用户是否已通过身份验证。

这是我的代码在相关部分中的样子。

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 thru my logic to trigger the LOGIN action, I can see that the mutation executed properly, and when I use the Chrome extension to view the vuex state for my core module, the state for user and authenticated have been properly mutated.

QUESTION

It seems like this module just simply has not been loaded by the time the router is running in the .beforeEach loop. Is this true?

If yes, what are some other suggestions on how to handle this situation? If no, what am I doing incorrect?

第4056篇《在beforeEach期间将vuex模块状态传递到vue-router》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android