How does the navigation guard of vue-router judge the value of cookies or vuex

first of all, before the user logs in, I want to determine whether the user is logged in according to the value stored in cookies or vuex. If cookies logs in, it will store the userId and userName fields.

then, my vuex goes like this:

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
    }
  }
})

that is to judge whether a user is logged in according to nickName

finally, I wrote this on vue-router "s 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; // 
  // ;nextRoutelogin
  if (nextRoute.indexOf(to.name) >= 0) {
    if (!nickName) {
      router.push({
        name: "Login"
      })
    }
  }
  // ;loginhome 
  if (to.name === "Login") {
    if (nickName) {
      router.push({
        name: "Index"
      });
    }
  }
  next();
});

but remind me that this is wrong. I want to know how to write it correctly
const nickName = router.app.$store.state.nickName; / / whether to log in to
is the above sentence misspelled? Do you have a partner to tell you how to judge the value of vuex or cookies? How to get userName of cookies or niceName? of vuex by nickName

Feb.28,2021

I judge when I enter the outermost route in 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()
        }
    }
}]

const nickName = router.app.$store.state.nickName; / / whether to log in

in the callback function through router.beforeEach, you can get the root instance of the entire App through router.app.

you can view the $store attribute in the properties of the root instance through console.log (router.app).

but the goose call doesn't get the value and returns undefined, directly. I don't know why?

Menu