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

Viewed 70

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.

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

Are there any drawbacks to the second method?

1 Answers

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.

Related