Open In App

How to Go Back/Route-Back on Vue-Router ?

Last Updated : 05 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Vue Router is a navigation library designed specifically for Vue.js applications. It empowers developers to construct single-page applications, with dynamic and client-side routing capabilities. A frequent need in web applications is the ability to navigate back or return to the previous page. In this article, we will delve into two different approaches to accomplish this task as listed below:

Steps to Setup the Project Environment

Step 1: Create a VueJS application using the below command.

 npm create vue@latest 

Step 2: Navigate to the project that you have just created by this command.

cd your-project-name

Step 3: Run this command to install all packages

npm install

Step 4: Now, Set up vue router using below command.

npm install vue-router@4

Step 5: Create a folder inside src named views. Inside it, we will put all our components.

Step 6: Create components inside the views folder as listed below:

  • AboutView.vue
  • ContactView.vue
  • HomeView.vue

Step 7: Create another file inside src named router.js. It will handle the routes of the application.

Step 8: Now, Create a navbar inside the App.vue file to navigate easily around the webpage.

Step 9: Add the below code to main.js. It is the starting point of our application.

// src/main.js file
const { createApp } = require('vue');
import App from './App.vue';
import createRouter from './router';
createApp(App).use(createRouter()).mount('#app');

Project Structure

routerStr

Using the go() method

The go(n) method allows you to navigate to a specific position. The parameter n is an integer that represents the number of steps to go forward (positive) or backward (negative).

Syntax:

router.go(n)

Example: The below JavaScript codes will help you implement the go() method to go back on a page.

Javascript




<!-- src/App.vue file -->
 
<script>
import { RouterView, RouterLink, useRouter, useRoute } from "vue-router";
export default {
  name: "#app",
  setup() {
    const router = useRouter();
    const route = useRoute();
 
    function goBackUsingBack() {
      if (router) {
        router.back();
      }
    }
 
    return { router, route, goBackUsingBack };
  }
}
</script>
<template>
  <nav>
    <RouterLink to="/">Home</RouterLink> |
    <RouterLink to="/contact">Contact</RouterLink> |
    <RouterLink to="/about">About</RouterLink><br/><br/>
    <button @click="goBackUsingBack">Go Back Using Back method</button>
  </nav>
  <RouterView />
</template>
<style>
nav {
  width: 100%;
  font-size: 24px;
}
 
nav a {
  display: inline-block;
  padding: 5px 10px;
  margin: 10px;
}
 
nav a.router-link-exact-active {
  background-color: green;
  text-decoration: none;
  color: #fff;
}
</style>


Javascript




// src/router.js
 
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from './views/HomeView.vue';
import ContactView from './views/ContactView.vue';
import AboutView from './views/AboutView.vue';
 
const router = () =>
  createRouter({
    history: createWebHistory(),
    routes: [
      {
        path: '/',
        name: 'home',
        component: HomeView,
      },
      {
        path: '/about',
        name: 'about',
        component: AboutView,
      },
      {
        path: '/contact',
        name: 'contact',
        component: ContactView,
      },
    ],
  });
 
export default router;


Javascript




// src/main.js file
 
const { createApp } = require('vue');
import App from './App.vue';
import createRouter from './router';
 
createApp(App).use(createRouter()).mount('#app');


Javascript




<!-- views/ContactView.vue file -->
 
<template>
<h1>This is Contact Page</h1>
</template>
<script>
      export default {}
</script>


Javascript




<!-- views/ContactView.vue file -->
 
<template>
<h1>This is Contact Page</h1>
</template>
<script>
      export default {}
</script>


Javascript




<!-- views/AboutView.vue file -->
 
<template>
      <h1>This is About Page</h1>
</template>
<script>
      export default {};
</script>


Output:

goBackGIF

Using back() method

This method is specifically used to navigate back to the previous page in the history, similar to pressing the browser’s back button. You just need to replace your App.vue file with the below file to implement this approach.

Syntax:

router.back()

Example: The below example implements the back() method to go back on a page.

Javascript




<!-- src/App.vue file -->
 
<script>
import { RouterView, RouterLink, useRouter, useRoute } from "vue-router";
export default {
  name: "#app",
  setup() {
    const router = useRouter();
    const route = useRoute();
 
    function goBackUsingBack() {
      if (router) {
        router.back();
      }
    }
 
    return { router, route, goBackUsingBack };
  }
}
</script>
<template>
  <nav>
    <RouterLink to="/">Home</RouterLink> |
    <RouterLink to="/contact">Contact</RouterLink> |
    <RouterLink to="/about">About</RouterLink><br/><br/>
    <button @click="goBackUsingBack">
        Go Back Using Back method
    </button>
  </nav>
  <RouterView />
</template>
<style>
nav {
  width: 100%;
  font-size: 24px;
}
 
nav a {
  display: inline-block;
  padding: 5px 10px;
  margin: 10px;
}
 
nav a.router-link-exact-active {
  background-color: green;
  text-decoration: none;
  color: #fff;
}
</style>


Javascript




// src/router.js
 
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from './views/HomeView.vue';
import ContactView from './views/ContactView.vue';
import AboutView from './views/AboutView.vue';
 
const router = () =>
  createRouter({
    history: createWebHistory(),
    routes: [
      {
        path: '/',
        name: 'home',
        component: HomeView,
      },
      {
        path: '/about',
        name: 'about',
        component: AboutView,
      },
      {
        path: '/contact',
        name: 'contact',
        component: ContactView,
      },
    ],
  });
 
export default router;


Javascript




// main.js file
 
const { createApp } = require('vue');
import App from './App.vue';
import createRouter from './router';
 
createApp(App).use(createRouter()).mount('#app');


Javascript




<!-- views/HomeView.vue file -->
 
<template>
<h1>This is Home Page</h1>
</template>
<script>
  export default {}
</script>


Javascript




<!-- views/ContactView.vue file -->
 
<template>
<h1>This is Contact Page</h1>
</template>
<script>
  export default {}
</script>


Javascript




<!-- views/AboutView.vue file -->
 
<template>
  <h1>This is About Page</h1>
</template>
<script>
  export default {};
</script>


Output:

goBackGIF

Conclusion:

Navigating within a Vue.js application using Vue Router is pretty simple. You can implement navigation effortlessly by utilizing the back() and go() methods. It’s also important to handle any situations to ensure an user experience regardless of whether users navigate naturally or land directly, on a particular page. Having a grasp of these navigation techniques will allow you to create interactive and user friendly Vue.js applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads