'Is it possible to get the clicked element that triggers a route change from the Vue router?
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?
Solution 1:[1]
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.
- 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
beforeRouteLeaveguards in deactivated components. - Call global
beforeEachguards. - Call
beforeRouteUpdateguards in reused components. - Call
beforeEnterin route configs. - Resolve async route components.
- Call
beforeRouteEnterin activated components. - Call global
beforeResolveguards. - Navigation is confirmed.
- Call global
afterEachhooks. - DOM updates triggered.
- Call callbacks passed to next in
beforeRouteEnterguards with instantiated instances.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
