<button @click="logout">Logout</button>
export default {
fetch ({store, redirect}) {
if (!store.state.authUser) {
return redirect('/login')
}
},
methods: {
logout () {
this.$store.dispatch('logout');
// this.$nuxt.$router.replace({ path: 'login' });
// this.$nuxt.$router.replace({ path: 'test' });
window.location.href = 'login';
}
}
}
In this case, when i use this.$nuxt.$router.replace({ path: 'test' }), i am redirected to localhost:3000/test and it requested localhost:3000/api/users/test at the sametime.
But when i use this.$nuxt.$router.replace({ path: 'login' }), it didn't redirect. And in vue-dev-tools, i can see it didn't emit an routeChanged event.
As a workaround, i use window.location.href = 'login' temporarily.
I don't know if $router in a method page is the right way to browser redirects.
Thanks in advance for awesome nuxt.
Hi @solarhell - I think you are looking for ...router.push(location) - see vue router (programmatic) navigation.
Hi @solarhell
If this.$store.dispatch('logout') sends back a Promise, you should wait that it finished before redirecting the user, to make sure that your store is updated:
methods: {
logout () {
this.$store.dispatch('logout')
.then(() => this.$router.replace({ path: 'login' }))
}
}
What I found weird is isn't this.$router.go() made for situations like this? Why does this not work?
it works!
this.$router.replace() replaced with this.$router.go()
this.$store.dispatch('logout').then(() => this.$router.go({ path: 'login' }))
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Hi @solarhell
If
this.$store.dispatch('logout')sends back a Promise, you should wait that it finished before redirecting the user, to make sure that your store is updated: