Dave
Dave

Reputation: 2601

Vue.js Push and the back button

I have a list of items in a Vue.js template. The user starts at '/list', which is a list of items. When an item is clicked, I use $router.push to send the user to a route. The route I send the user to is:

$router.push('/items/[theItemId]/Property1');

I do this so the user doesn't have to ever be on ' /items/[theItemId]'. This is working great, however when the user hits the back button, they are taken to the route:

/items/[theItemId]

I instead want the user to be directed back to the main list.

'/list'

Is this possible to do?

Thanks

Upvotes: 0

Views: 3284

Answers (1)

Mani Jagadeesan
Mani Jagadeesan

Reputation: 24265

I think you are using $router.push in the created or mounted hook of your route component for /items/:itemID.

When you use $router.push, a new item in history stack gets created. So your history stack now looks as follows:

/list >> /items/:itemID >> /items/:itemID/Property1

As the back button generally takes you to the previous entry in your history stack, it takes you to /items/:itemID as expected.

To avoid this, you may use $router.replace instead of $router.push as explained here:

https://router.vuejs.org/en/essentials/navigation.html

Quoted from the page above:

router.replace(location)

It acts like router.push, the only difference is that it navigates without pushing a new history entry, as its name suggests - it replaces the current entry.

If you use $router.replace, your history stack now will be:

/list >> /items/:itemID/Property1

Now if you hit the back button, you will end up in /list.

Upvotes: 5

Related Questions