How can I go back/route-back on vue-router?

John107 picture John107 · Jan 5, 2018 · Viewed 95.8k times · Source

Ok, to explain this simply:

I have 3x pages.

  • Page 1 (Home)
  • Page 2 (Menu)
  • Page 3 (About)

Page 1 has a-

<router-link  to="/menu">

button that when clicked routes to "/menu".

For now, Page 2 (Menu) has a

<router-link  to="/">

button and when this button is clicked it reverts to the previous location "/" Page 1 (Home).

But I don't want to create a component for router for each page to 'go back' to the previous page (as if I had 100 pages this could be a lot of work routing back). Is there a way to do this with vue-router? similar to window.history.back()

Curious to see if there is a way to do this as I can't find it in the docs.

Thanks in advance! John

Answer

Jos&#233; Fernando Davila picture José Fernando Davila · Jan 6, 2018

You can use Programmatic Navigation.In order to go back, you use this:

router.go(n) 

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>