ptk
ptk

Reputation: 7653

How does the next() guard function in vue-router work?

I'm trying to understand the solution in this SO post. The solution allows the user to keep track of the previous route in the current route.

Below is the snippet of Vue code that I'm trying to understand. If I understand correctly, next accepts a callback function that receives the current component's vue instance. We then set the prevRoute data property of this vue instance to from. Is this interpretation correct? If not, what is actually happening?

If someone could also add a brief explanation as to what the Vue API is doing behind the scenes that would also be very helpful for me to actually understand the snippet of code.

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

Upvotes: 2

Views: 1079

Answers (1)

Phil
Phil

Reputation: 164894

As per the documentation...

The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.

However, you can access the instance by passing a callback to next. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument

So vm is the component instance assigned to the destination route.


From your question...

We then set the prevRoute data property of this vue instance to from. Is this interpretation correct?

Almost. All you're doing is setting a direct object property on the Vue component which is after all, just a JavaScript object at heart. For example

const vm = { name: 'I am totally a Vue component' }
vm.prevRoute = from

This property will not be reactive but you can certainly access it within your component via this, just as you can other non-data properties like $el, $refs, etc.

Upvotes: 2

Related Questions