我将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
}
当我通过逻辑触发LOGIN
操作时,我可以看到突变正确执行,当我使用Chrome扩展程序查看我的core
模块的vuex状态时, user
和authenticated
的状态已正确变异。
问题
似乎这个模块在路由器在.beforeEach
循环中运行时才刚刚加载。这是真的吗?
如果是,有关如何处理这种情况的其他一些建议是什么? 如果不是,我做错了什么?
答案 0 :(得分:1)
console.log(store.state.core.authenticated)
返回false,因为您尚未登录。
在您的代码中,您不会在任何地方保留用户信息。例如。使用localstorage
同样的考虑因素:
router.app.$store
,请使用您导入的store
LOGIN_SUCCESS
突变中,将登录信息和令牌存储到localstorage beforeEach
挂钩中,检查localstorage,如果填充了令牌,请获取用户信息并应用突变。如果没有,请拨打登录页面像这样......
const mutations = {
[types.LOGIN_SUCCESS] (state, payload) {
state.token = payload.token
state.user = payload.user
state.authenticated = true
localstorage.setItem('token', payload.token)
localstorage.setItem('user', payload.user)
}
}
const actions = {
[types.LOGIN] (context, payload) {
return api.getToken(payload).then(response => {
context.commit(types.LOGIN_SUCCESS, response)
return response
})
}
}
router.beforeEach((to, from, next) => {
let user = localstorage.getItem('user')
let token = localstorage.getItem('token')
if (user && token) {
store.commit(types.LOGIN_SUCCESS, {token, user})
next()
}
else if (!store.getters.isAuthenticated) {
store.dispatch(types.LOGIN).then(() => next())
} else {
next()
}
}