Nuxt.js: `this.$router.replace` not works well

Created on 5 Feb 2017  路  5Comments  路  Source: nuxt/nuxt.js

<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.

This question is available on Nuxt.js community (#c174)

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:

methods: {
    logout () {
      this.$store.dispatch('logout')
      .then(() => this.$router.replace({ path: 'login' }))
    }
  }

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bimohxh picture bimohxh  路  3Comments

maicong picture maicong  路  3Comments

vadimsg picture vadimsg  路  3Comments

jaredreich picture jaredreich  路  3Comments

shyamchandranmec picture shyamchandranmec  路  3Comments