VueJS

Vue.js Vue-Router Navigation - Programmatically Changing Routes


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>

            

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.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.