Introducing Vue-Router and Loading URL-Based Components Chapter 8
Navigating programmatically
You may want to alter the path, URL, or user flow from the code, a component, or action.
An example of this might be sending the user to the basket after they've added an item.
To do this, you use a push() function on the router instance. The value of push can either
be a string for a direct URL or it can accept an object to pass named routes or route
parameters. The allowed contents of the push function are exactly the same as the to=""
attribute on the router-link element. For example:
const About = {
name: 'About',
template: '#about',
methods: {
someAction() {
/* Some code here */
// direct user to contact page
this.$router.push('/contact');
}
}
};
Alternatively, you could direct to a named route with parameters:
this.$router.push({name: 'user', params: { name: 'sarah', emotion: 'happy'
}});
Redirecting
Redirecting using VueRouter is fairly straightforward. An example of a redirect might be if
you move your /about page to the /about-us URL. You will want to redirect the first
URL to the second, in case anyone has shared or bookmarked your link, or in case a search
engine has cached the URL.
You may be tempted to create a basic component which, when created, uses the
router.push() function to send the user to the new URL.