Reputation: 7160
I have a problem when I use router.push('/')
as the last step of a logout.
If I trigger the logout procedure from the same route that /
redirect
s to, the router.beforeEach
will not be triggered and therefore not redirect the user to the /login
but still show the route that should only be visible to logged in users (which the user isn't any more at the end of the logout procedure).
{
path: '/',
redirect: 'foo'
},
{
path: '/foo',
name: 'foo',
component: Foo,
meta: {
requiresAuth: true
}
},
and
router.beforeEach((to, from, next) => {
...
if(to.requiresAuth && userLoggedIn == false)
next('/login')
...
So if I trigger the logout from any route other than /foo
it works as expected but if I trigger it from /foo
the user is not redirected to /login
.
I guess that might possibly be intended behaviour to make the routing as efficient as possible but in this case it is definitely not what I want.
How do I ensure my beforeEach
route guards will be evaluated on every router.push/replace
?
Upvotes: 7
Views: 3857
Reputation: 29917
Create a /logout
route which redirects to the /
route.
Bonus: Display a nice message with "Successfully logged out" and redirect after a couple of seconds.
Upvotes: 4
Reputation: 138696
The router.beforeEach
guard seems to run only when it detects a change in navigation. Since the route is the same in your case, you'd have to force a navigation change by pushing a different route path before your intended one. Pushing an empty space beforehand works well. This is admittedly hacky.
For example:
<button @click="$router.push(' '); $router.push('/')">Logout</button>
Upvotes: 3