从路由守卫重定向和从组件内的 mounted() 生命周期钩子重定向之间有区别吗?

Is there a difference between redirecting from a route guard and from the mounted() lifecycle hook inside a component?

假设有一个视图,我只希望登录用户可以访问它。我可以通过在这样的路线上使用路线守卫来阻止访问:

    beforeEnter: (to, from, next) => {
        if (!store.getters.authenticated) {
            next({ name: "login" })
        } else {
            next()
        }
    }

但我想知道如果我使用 if 语句来确定用户是否登录在我要限制的组件的 mounted() 生命周期挂钩中是否是错误的。

mounted(){
    if(!store.getters.authenticated){
        router.push({name: "login"})
    }
}

第二种方法有什么缺点吗?

您可以使用路由器挂钩通过商店触发身份验证。

像这样:

beforeEnter: async (to, from, next) => {

    await store.dispatch(`login`);

    if (!store.getters.authenticated) {
        next({ name: `login` });
    } else {
        next();
    }
}

当然,您的组件中的自动登录逻辑必须移动到您商店的操作 + 变更中。