【发布时间】:2017-02-17 20:03:19
【问题描述】:
我将 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 状态时,@987654330 的状态@ 和 authenticated 已正确变异。
问题
看起来这个模块只是在路由器在.beforeEach 循环中运行时还没有加载。这是真的吗?
如果是,对于如何处理这种情况,还有哪些其他建议? 如果没有,我做错了什么?
【问题讨论】:
-
登录
store.state.core.authenticated会得到什么? -
@francoisromain
console.log(store.state.core.authenticated)返回false -
我想我找到了问题所在。但是,直到我做更多的研究......我不会发布我自己的答案。似乎状态不是持久的,并且没有使用 HTML5 localstorage 之类的东西。因此,在每次页面加载时,状态都是空的。所以,我需要将我的用户移动到本地存储(或类似的)以获得这种持久性。我有一个可行的解决方案,当我确定这是最好的方法时,我会发布它。
-
@TheBrewmaster 也许这会有所帮助.. github.com/Ridermansb/vuex-router-auth0-example
标签: javascript vue.js vue-router vuex