Blog>
Snippets

Programmatic Navigation in Vue.js 3

Using Vue Router's programmatic API to navigate between pages without anchor tags, by pushing, replacing, or going back in history programmatically.
import { createRouter, createWebHistory } from 'vue-router';

// Define some routes
// Each route should map to a component
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  // ...other routes
];

// Create the router instance
const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;
This is the setup for the Vue Router. It includes importing the necessary functions from 'vue-router', defining the routes, and creating the router instance with a history mode and the defined routes.
// In a Vue component
export default {
  methods: {
    // the navigation function
    navigateToAbout() {
      // Use the router.push method to navigate to the about page
      this.$router.push('/about');
    },
    replaceWithHome() {
      // Use the router.replace method to navigate to home without adding a history record
      this.$router.replace('/');
    },
    goBack() {
      // Use the router.go method to go one step back in the browser history
      this.$router.go(-1);
    }
  }
};
These are methods inside a Vue component that use Vue Router's programmatic navigation API. The 'navigateToAbout' method uses 'push' to navigate to the about page and add a record in history. The 'replaceWithHome' method uses 'replace' to navigate to the home page without adding a history record. The 'goBack' method uses 'go' to go one step back in the browser history.