Introduction

Vue Router allows you to programmatically navigate between different routes in your Vue.js application. This is useful when you want to change routes based on user interactions or application logic. In this guide, we'll explore how to programmatically change routes using Vue Router and provide sample code to demonstrate the process.


Sample Code

Let's create a Vue.js application with Vue Router and define a button that, when clicked, navigates to a different route programmatically:


<div id="app">
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
<button @click="goToAboutPage">Go to About Page</button>
<router-view></router-view>
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
const app = new Vue({
router,
el: '#app',
methods: {
goToAboutPage() {
// Programmatically navigate to the About page
this.$router.push('/about');
}
}
});
const Home = {
template: '<div>This is the Home page</div>'
};
const About = {
template: '<div>This is the About page</div>'
};

In this code:

  • We create a Vue component that includes `router-link` elements for the "Home" and "About" routes. We also define a button that triggers a method to navigate to the "About" page.
  • We configure Vue Router with two routes: "Home" and "About," each associated with a component.
  • We create a Vue method, `goToAboutPage`, that uses `this.$router.push('/about')` to programmatically navigate to the "About" page when the button is clicked.