Paulund

VueJS - Vue Router Change Page

Sometimes while you're developing you find situations where you need to redirect to a different page or go back to the last page. For example you could have a form that allows you to delete a record and on a successful delete you're redirected back a page to see the full list of the records. Using the Vue Router object you're able to navigate to any URL or navigate the history of your application, this is done by using the router.push( path ).

router.push( path );

This is the same as using the router-link tag <router-link :to=""></router-link> and the user clicking on this link but it can be redirected in your code. There are a number of ways you can use the push method, either with a string URL.

router.push( '/contact' );

Or you can use an route object and pass in the path you want to use.


router.push( { path: '/contact' } );

If you have named routes then you can call the name of the route instead, I believe named routes are better process to use, because if your routes change you only need to change them in one place.

router.push({ name: 'contact' })

The push method will add a history record into the browser so after going to the new URL you're able to use router.go(-1) to go back to the previous URL entry. The go() method allows you to navigate the history of the application allowing you to go forwards or backwards through the history.

// Go back one page
router.go(-1)

// Go forward a page
router.go(1)

These are similar to the standard Javascript window.history API if you're already familiar with this API then you will easily understand the vue router go() and push() methods.