Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue-router - How to get previous page url?

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); 
like image 208
narupo Avatar asked Dec 15 '18 02:12

narupo


People also ask

How do I go to another page in Vue?

If you are using vue-router , you should use router.go(path) to navigate to any particular route. The router can be accessed from within a component using this. $router .

What is history mode in Vue router?

The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. To get rid of the hash, we can use the router's history mode, which leverages the history.

How do I find the current path on my Vue router?

We can use this. $router. currentRoute. path property in a vue router component to get the current path.


2 Answers

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.

like image 175
Husam Ibrahim Avatar answered Oct 05 '22 10:10

Husam Ibrahim


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.

like image 39
David Becerra Montellano Avatar answered Oct 05 '22 11:10

David Becerra Montellano