I have a button that triggers a route change within my Vue application. I want the button element to be accessible in the component's $route object as the "event target" of the route change (similar to how there's an event.target in a click event).
Is that possible?
If not, what would be the best way to obtain the cause of the route change?
CodePudding user response:
You are looking for Navigation Guards. There are
- Global navigation guards that are called on each route beforeEnter/resolve/leave/after depending on the type of guard you used.
- Per-route navigation guards that are used in your router file, inside each route's declaration. 3)
- In-Component Guards that are used inside components.
You can get the specific button that caused the route change in your component inside the In-Component Guard beforeRouteLeave(to, from)
. This specific guard has access to this
of the component which has all the props and reactive state (including the button reference).
According to the docs, this is how each guard falls in the flow of a navigation action:
- Navigation triggered.
- Call
beforeRouteLeave
guards in deactivated components. - Call global
beforeEach
guards. - Call
beforeRouteUpdate
guards in reused components. - Call
beforeEnter
in route configs. - Resolve async route components.
- Call
beforeRouteEnter
in activated components. - Call global
beforeResolve
guards. - Navigation is confirmed.
- Call global
afterEach
hooks. - DOM updates triggered.
- Call callbacks passed to next in
beforeRouteEnter
guards with instantiated instances.