Vue-router login status detection?

there are three pages in total. By default, they point to the login page. After logging in, you can store client_id to cookie and global.CLIENT_ID

.

what I want to do is to check the login status. When the page jumps, check that global.CLIENT_ID or cookie, does not exist and then jump to the login page.

// 
import main from "./components/main/main.vue";
import star from "./components/star/star.vue";
import login from "./components/login/login.vue";


// 
const routes = [
    {
        name: "main",
        path: "/main",
        component: main,
        // meta: {
        //     login_required: true
        // }
    },
    {
        name: "star",
        path: "/star",
        component: star,
        // meta: {
        //     login_required: true
        // }
    },

    {
        name: "login",
        path: "/login",
        component: login,
        // meta: {
        //     login_required: false
        // }
    },
    {
        path: "/",
        redirect: "/login"
    }
];

const router = new VueRouter({
    routes: routes
});

new Vue({
    el: "-sharpapp",
    components: {App},
    template: "<App/>",
    router: router
})

I asked some related questions about Baidu. Some people said that router hooks could be used, but I tried

.
router.beforeEach(function (to, from, next) {
    if(to.name === "main" || to.name === "star"){
        next("/login");
    }

    else{
        next();
    }

});

even so, there will be two problems:
1. If you enter http://localhost:8080/-sharp/main directly in the browser address bar, you can skip logical access to main
2. The current page is main,. Clicking star once will jump to login, but clicking star, again will jump to star.

.

I also tried to watch global.CLIENT_ID, in main.js but mistakenly reported that there was too much recursion.

Please give me a train of thought, or related code, thank you.

Mar.13,2021

after reading the title of the landlord, I will have the benefit of hindsight.

this is vue-router 's description of navigation guards

clipboard.png

beforeEach/afterEach

router.onReady

clipboard.png

this is how I solved this in my own project. As for login status, it is recommended to use vuex's state to save it.


it is correct to write in the route interception, but you have not figured out the way to go down.
if you want to go to the landing page, do not judge whether there is local information
if you are going to another page, you have local login information and have not timed out, otherwise you will go to the landing page
show my code

.
    if(to.name==="login"){
        next();
    }else{
        if(loginInfo){
            // 
            next()
        }else{
            next("login")
        }
    }

another big shot's answer, for reference:
https://codeshelper.com/q/10.


if (to.name === 'login') {
  next('/login')
}
if (global.CLIENT_ID) {
  next()
} else {
  next('/login')
}
Menu