鍍金池/ 問答/Java  C  HTML/ vue-router的導(dǎo)航守衛(wèi)如何判斷cookies或者vuex的值

vue-router的導(dǎo)航守衛(wèi)如何判斷cookies或者vuex的值

首先,我想在用戶登錄前,根據(jù)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
    }
  }
})

即根據(jù)nickName判斷用戶是否登錄

最后,我在vue-router的index.js這么寫:

  // 全局路由守衛(wèi)
  router.beforeEach((to, from, next) => {
  console.log('導(dǎo)航守衛(wèi)(navigation-guards)');
  // to: Route: 即將要進入的目標(biāo) 路由對象
  // from: Route: 當(dāng)前導(dǎo)航正要離開的路由
  // next: Function: 一定要調(diào)用該方法來 resolve 這個鉤子。執(zhí)行效果依賴 next 方法的調(diào)用參數(shù)。

  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; // 是否登錄
  // 未登錄狀態(tài);當(dāng)路由到nextRoute指定頁時,跳轉(zhuǎn)至login
  if (nextRoute.indexOf(to.name) >= 0) {
    if (!nickName) {
      router.push({
        name: 'Login'
      })
    }
  }
  // 已登錄狀態(tài);當(dāng)路由到login時,跳轉(zhuǎn)至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里,然后進入最外層的路由時判斷:

let routes = [{
    path: '/login',
    component: Login,
    name: 'login'
},{
    path: '/admin',
    component: Admin,
    beforeEnter: (to, from, next) => {
        if(!localStorage.ACCOUNT || localStorage.ACCOUNT == ''){
            next({
                name: 'login'
            })
        }else{
            next()
        }
    }
}]
2017年1月31日 00:33