0

I'm using Nuxt and I have a problem with the $router.back() method.

When I come from outside the application and I return ($router.back()), I am redirected outside my application.

I would like to be redirected to the reception if I don't have a route history.

How can I do please?

<template>
  <a href="#" @click="hasHistory() ? $router.back() : $router.push('/')">
    <font-awesome-icon :icon="['fas', 'chevron-left']" class="fa-fw" /> Retour
  </a>
</template>

<script>
export default {
  methods: {
    hasHistory() {
      return window.history.length > 1
    },
  },
}
</script>
kissu
  • 40,416
  • 14
  • 65
  • 133
jeyGey
  • 161
  • 3
  • 15

2 Answers2

0

After some research, I found out that you cannot access a full history of the previous visited URLs (for security reasons).

So, you should probably make one yourself. The idea would be to:

  • have a middleware that is pushing the current path of your SPA to some array in Vuex like myWebsiteHistory
  • when you want to go back (with the mouse or the arrow of your browser I guess?), you could check the array and see if it's empty or not
  • if it's empty, send the user to the index page
  • otherwise, move to the last pushed - 1 path (via vue-router still)

This may seem cumbersome but it's because it's not really something that you may want on your website

as a user, if I want to leave a website, I press back and I go back

Here, you'll be basically saying f*ck you to your visitor by hijacking the behavior of his browser. And yeah, also the security/tracking issues. Hence why nothing has been implemented in a simpler way yet IMO.

kissu
  • 40,416
  • 14
  • 65
  • 133
0

Thank you for your answer.

I found solution:

<template>
    <div>
        <a @click="hasHistory() ? $router.back() : $router.push('/')" href="#">
            <font-awesome-icon :icon="['fas', 'chevron-left']" class="fa-fw"/> Retour
        </a>
    </div>

</template>

<script>
    export default {
        methods: {
            hasHistory() {
                return this.$nuxt.context.from;
            }
        }
    }
</script>
jeyGey
  • 161
  • 3
  • 15