How to create back button using NuxtJS <nuxt-link />?

Viewed 9606

I have a fairly new Nuxt project I'm working on, and I'm running in to an issue setting up a back button. I even looked at the "vue-router-back-button" package which still doesn't want to work (I was getting unrelated errors). With the code that I have, the link wants to navigate to the same page that the user is currently on, rather than the one previous. I do receive an error on my server that there is an Invalid prop: type check failed for prop "to". Expected String, Object, got Function., however would I make the back button dynamic?

<template>
  <div class="page-title-wrapper">
    <nuxt-link
      v-if="back"
      :to="to"
      class="back-wrapper">
      <icon
        name="angle-left"
        fill="#9e9e9e"
        height="20px"
        width="20px"
        class="d-flex" />
      <p class="display-1 grey--text">
        Back
      </p>
    </nuxt-link>
    <h1 class="display-3 text-center">
      {{ text }}
    </h1>
  </div>
</template>

<script>
  export default {
    props: {
      back: {
        type: Boolean,
        default: false,
      },
      text: {
        type: String,
        default: 'Page'
      }
    },

    methods: {
      to() {
        this.$router.go(-1);     <---- evaluates to current page?
      },
    }
  }
</script>
2 Answers

this.$router.go(-1)

The command to go back one history step using Vue Router (which Nuxt uses):

this.$router.go(-1)

With a click listener, trigger it within a function, like so:

Template:

<div @click="goToPrev()">My Button</div>

Method:

methods: {
  goToPrev() {

    // ...
    // Do other logic like logging, etc.
    // ...

    // Tell router to go back one
    this.$router.go(-1);
  },
}

Another example:

Using the Vuetify framework and their button element (<v-btn>):

  <template>  
    <v-btn text :ripple="false" class="back-wrapper" @click="to">
      <icon name="angle-left" fill="#9e9e9e" height="20px" width="20px" class="d-flex" />
      <p class="display-1 grey--text">
        Back
      </p>
    </v-btn>
  </template>

  <script>
    methods: {
      to() {
        this.$router.go(-1)
      },
    }
  </script>

You can also use this by checking window history length. If window history is 1 or less than 1 then it's going back to your home page. More usable.

 window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
Related