首先,我想在用户登录前,根据cookies或者vuex存储的值判断用户是否登录,cookies如果登录了的话,会存userId和userName两个字段。
然后,我的vuex是这样的:
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
nickName: '',
activeIndex: ''
},
mutations: {
updateUserInfo(state, nickName) {
state.nickName = nickName;
},
updateNavHeaderActiveIndex(state, activeIndex) {
state.activeIndex = activeIndex
}
}
})
即根据nickName判断用户是否登录
最后,我在vue-router的index.js这么写:
// 全局路由守卫
router.beforeEach((to, from, next) => {
console.log('导航守卫(navigation-guards)');
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
const nextRoute = ['MyOrgIndex', 'AddTopic', 'TopicComment', 'OrgIndex', 'AddOrg', 'OrgDetail', 'MemberList', 'UserIndex', 'ChangeUserInfo', 'ChangeUserPassword', 'MktIndex', 'AddNewGoods', 'MyCollection', 'GoodDetail', 'myGoods', 'ContactsIndex', 'ContactsContent', 'ContactsDetail', ];
const nickName = router.app.$store.state.nickName; // 是否登录
// 未登录状态;当路由到nextRoute指定页时,跳转至login
if (nextRoute.indexOf(to.name) >= 0) {
if (!nickName) {
router.push({
name: 'Login'
})
}
}
// 已登录状态;当路由到login时,跳转至home
if (to.name === 'Login') {
if (nickName) {
router.push({
name: 'Index'
});
}
}
next();
});
但是提示我这是错误的,想知道到底要怎么写才是对的
const nickName = router.app.$store.state.nickName; // 是否登录
是不是上面这句话写错了?有没有小伙伴说下vuex或者cookies如何判断取值?nickName如何获得cookies的userName或者vuex的niceName?
我是存在
localstorage
里,然后进入最外层的路由时判断: