vue-router - How to get previous page url?

vue.jsVue Router

vue.js Problem Overview


I want to get previous page link or url in vue-router. Like a this. How to do it?

const link = this.$router.getPrevLink(); // function is not exist?
this.$router.push(link);

Near concept is this.$router.go(-1).

this.$router.go(-1);

vue.js Solutions


Solution 1 - vue.js

All of vue-router's navigation guards receive the previous route as a from argument ..

> Every guard function receives three arguments: > > - to: Route: the target Route Object being navigated to. > > - from: Route: the current route being navigated away from. > > - next: Function: this function must be called to resolve the hook. The > action depends on the arguments provided to next

As an example you could use beforeRouteEnter, an in-component navigation guard, to get the previous route and store it in your data ..

...
data() {
 return {
   ...
   prevRoute: null
 }
},
beforeRouteEnter(to, from, next) {
  next(vm => {
    vm.prevRoute = from
  })
},
...

Then you can use this.prevRoute.path to get the previous URL.

Solution 2 - vue.js

My solution was:

this.$router.options.history.state.back

The final code:

export default defineComponent({
  name: 'Error404',
  data () {
    return {
      lastPath: null
    }
  },
  created () {
    this.lastPath = this.$router.options.history.state.back
  },
  computed: {
    prevRoutePatch () {
      return this.lastPath ? this.lastPath : '/dashboard'
    }
  }
})

Regards.

Solution 3 - vue.js

Though this answer is great, the received route wouldn't always be the route before in history in case of popstate navigations (aka when the user clicks the back button).

So if you use Vuex here's a code snippet that respects this behavior:

const store = new Vuex.Store({
  state: {
    routerHistory: [],
  },
});

const router = new VueRouter({
  mode: 'history',
  scrollBehavior(to, from, savedPosition) {
    const fromHistory = Boolean(savedPosition);

    if (fromHistory && store.state.routerHistory.length > 0) {
      store.state.routerHistory.splice(-1, 1);
    } else {
      store.state.routerHistory.push(from);
    }

    return savedPosition || { x: 0, y: 0 };
  },
});

Once implemented, you can define a getter for the previous route inside your store:

const store = new Vuex.Store({
  // ...
  getters: {
    previousRoute: (state) => {
      const historyLen = state.routerHistory.length;
      if (historyLen == 0) return null;
      return state.routerHistory[historyLen - 1];
    },
  },
});

This code uses the scrollBehavior hook, which only receives the savedPosition argument if it was a popstate navigation. Thanks to Vuex we can then store all the routes in an array (over multiple pages).

Solution 4 - vue.js

This routing solution will fall back to a static url if a previous url does not exist.

<template>
    <div>
        <router-link :to="prevRoutePath">Previous Page</router-link>
        <router-link to="/">Home Page</router-link>
    </div>
</template>

<script>
export default {
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.prevRoute = from;
        });
    },
    computed: {
        prevRoutePath() {return this.prevRoute ? this.prevRoute.path : '/'},
    }
}
</script>

Solution 5 - vue.js

To yank it right out of the $router object, use this in your computed or methods:

lastRouteName: function() {
  let returnVal = '';

  const routerStack = this.$router.history.stack;
  const idx = this.$router.history.index;

  if (idx > 0) {
    returnVal = routerStack[idx - 1].name;
  }

  return returnVal;
}

That'll return the route name, but you can also return the .path or whatever other property if you like.

To inspect the history object, do console.log(this.$router.history);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnarupoView Question on Stackoverflow
Solution 1 - vue.jsHusam IbrahimView Answer on Stackoverflow
Solution 2 - vue.jsDavid Becerra MontellanoView Answer on Stackoverflow
Solution 3 - vue.jsgarzjView Answer on Stackoverflow
Solution 4 - vue.jsLiakosView Answer on Stackoverflow
Solution 5 - vue.jsJohnM_3948View Answer on Stackoverflow