How to Use beforeRouteEnter in Vue Router
Use
beforeRouteEnter in a Vue component to run code before the route is confirmed. It receives to, from, and next arguments, and lets you delay navigation or fetch data before the component is created. Since the component instance is not yet available, you access it inside next callback.Syntax
The beforeRouteEnter guard is a function inside a Vue component's export default object. It takes three parameters:
- to: the target route object you are navigating to
- from: the current route you are navigating away from
- next: a function to control navigation flow
You cannot access this inside beforeRouteEnter because the component instance is not created yet. To access the component instance, pass a callback to next.
javascript
beforeRouteEnter(to, from, next) { // run code before entering route next(vm => { // vm is the component instance }) }
Example
This example shows a Vue component using beforeRouteEnter to fetch user data before the route loads. It delays navigation until data is ready and then sets it on the component.
javascript
import { ref } from 'vue'; export default { name: 'UserProfile', setup() { const user = ref(null); return { user }; }, beforeRouteEnter(to, from, next) { fetch(`https://jsonplaceholder.typicode.com/users/${to.params.id}`) .then(res => res.json()) .then(data => { next(vm => { vm.user = data; }); }) .catch(() => { next(false); // cancel navigation on error }); }, template: ` <div v-if="user"> <h2>User: {{ user.name }}</h2> <p>Email: {{ user.email }}</p> </div> <div v-else> Loading... </div> ` };
Output
When navigating to /user/1, the page shows 'User: Leanne Graham' and 'Email: Sincere@april.biz' after loading.
Common Pitfalls
- Cannot use
thisinsidebeforeRouteEnter: The component instance is not created yet, sothisis undefined. - Forgetting to call
next: Navigation will hang ifnextis not called. - Not handling errors in async calls: If fetching data fails, navigation should be canceled or redirected.
javascript
export default { beforeRouteEnter(to, from, next) { // WRONG: trying to access this // console.log(this); // undefined // CORRECT: use next callback next(vm => { console.log(vm); // component instance }); } }
Quick Reference
beforeRouteEnter is called before the route is confirmed. Use it to:
- Fetch data before entering a route
- Delay navigation until async tasks finish
- Access the component instance only inside
nextcallback
Remember to always call next() to continue navigation or next(false) to cancel.
Key Takeaways
Use beforeRouteEnter to run code before the route loads but before the component is created.
Access the component instance only inside the next callback passed to next().
Always call next() to continue navigation or next(false) to cancel it.
Handle async operations carefully to avoid navigation hanging.
Do not use this inside beforeRouteEnter because the component instance is not available yet.