nuxt router go back

Nuxt Router Go Back

If you are building a web application using Nuxt.js, there may come a time where you need to implement a "go back" functionality. This is where the user can click a button and be taken back to the previous page they were on. Luckily, the Nuxt.js router makes this relatively easy to implement.

Using the router's go method

The simplest way to implement a "go back" button in Nuxt.js is to use the router's go method. This method takes a single argument, which is the number of pages to go back in the history. So, to go back one page, you would call router.go(-1).

Here's an example implementation:


<template>
  <div>
    <button @click="goBack">Go back</button>
  </div>
</template>

<script>
export default {
  methods: {
    goBack() {
      this.$router.go(-1);
    }
  }
}
</script>

In this example, we have a button that calls the goBack method when clicked. This method simply calls this.$router.go(-1), which takes us back one page in the history.

Using the router's back method

The router also has a back method, which does the same thing as calling go(-1). This method can be useful if you want to provide a more descriptive label for your "go back" button.

Here's an example implementation:


<template>
  <div>
    <button @click="goBack">Go back</button>
  </div>
</template>

<script>
export default {
  methods: {
    goBack() {
      this.$router.back();
    }
  }
}
</script>

As you can see, the goBack method now calls this.$router.back() instead of this.$router.go(-1).

Finally, you can also implement a "go back" button using the router-link component. This component is used to create links between pages in your application, but it can also be used to create buttons that navigate between pages.

Here's an example implementation:


<template>
  <div>
    <router-link to="/" tag="button">Go back</router-link>
  </div>
</template>

In this example, we're using the router-link component to create a button that navigates back to the home page of our application. The tag attribute is used to specify that we want to render a button element instead of an a element.

So there you have it - three different ways to implement a "go back" button in Nuxt.js. Choose the method that works best for your particular use case!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe