简体   繁体   English

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

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

Imagine there's a view which I only want to be accessible by logged in users.想象有一个视图,我只希望登录用户可以访问它。 I can prevent the access by using a route guard on the route like this:我可以通过在路由上使用路由保护来阻止访问,如下所示:

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

But I was wondering if it'd be wrong if I used an if statement to determine if the user is logged in inside the mounted() lifecycle hook of the component I want to restrict.但是我想知道如果我使用 if 语句来确定用户是否在我要限制的组件的 mount() 生命周期钩子中登录,是否会出错。

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

Are there any drawbacks to the second method?第二种方法有什么缺点吗?

You can use the router hook to trigger the authentication via the store.您可以使用路由器挂钩通过商店触发身份验证。

Something like this:像这样的东西:

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

    await store.dispatch(`login`);

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

And of course the automatic login logic in your component would have to be moved to your store's actions + mutations.当然,您的组件中的自动登录逻辑必须移动到您商店的操作 + 突变中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM