0

<script>
export default {
  name: 'TEST',
   data() {
    return {
      prevRoute: ''
    }
  },
  methods: {
    goBack() {
      return this.$router.go(-1);
    },
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.prevRoute = from.name
      console.log(from.name)
    })
  },
}
</script>
<template> 
 <div>
  <button @click="goBack" class="back">{{ prevRoute }}</button>
 </div>
</template>

Vue router beforeRouteEnter - after refreshing the page, the button text {{ prevRoute }} disappears. What other ways are there to display text in the button of the previous page?

test
  • 1
  • 1
  • 1
    There are no ways. After refreshing current page is the first navigated route. Just output "Back" in case there's no name. – Estus Flask Sep 12 '21 at 06:47

1 Answers1

0

That's not possible at all, your from route will be always empty on refresh. The best approach I can figure out is by storing your route from.name in your localStorage and set that item only if from.name exists

beforeRouteEnter(to, from, next) {
    if (from.name) localStorage.setItem('from_route', from.name)
    next()
},        

Then in your mounted hook set the prevRoute value as per localStorage item

mounted () {
    this.from_route = localStorage.getItem('from_route')
},

Of course, you will face the same issue if someone shares you a link and you are not coming from any other page.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Luciano
  • 2,052
  • 1
  • 16
  • 26