Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Vue Router 4 reference covering navigation guards, route params, lifecycle interactions, and common gotchas.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
reference/router-beforerouteenter-no-this.md
1---2title: beforeRouteEnter Cannot Access Component Instance3impact: MEDIUM4impactDescription: The beforeRouteEnter guard runs before component creation, so 'this' is undefined; use the next callback to access the instance5type: gotcha6tags: [vue3, vue-router, navigation-guards, lifecycle, this]7---89# beforeRouteEnter Cannot Access Component Instance1011**Impact: MEDIUM** - The `beforeRouteEnter` in-component navigation guard executes BEFORE the component is created, meaning you cannot access `this` or any component instance properties. This is the ONLY navigation guard that supports a callback in the `next()` function to access the component instance after navigation.1213## Task Checklist1415- [ ] Use next(vm => ...) callback to access component instance16- [ ] Or use composition API guards which have different patterns17- [ ] Move data fetching logic appropriately based on timing needs18- [ ] Consider using global guards for data that doesn't need component access1920## The Problem2122```javascript23// Options API - WRONG: this is undefined24export default {25data() {26return { user: null }27},28beforeRouteEnter(to, from, next) {29// BUG: this is undefined here - component doesn't exist yet!30this.user = await fetchUser(to.params.id) // ERROR!31next()32}33}34```3536## Solution: Use next() Callback (Options API)3738```javascript39// Options API - CORRECT: Use callback to access vm40export default {41data() {42return {43user: null,44loading: true45}46},4748beforeRouteEnter(to, from, next) {49// Fetch data before component exists50fetchUser(to.params.id)51.then(user => {52// Pass callback to next() - receives component instance as 'vm'53next(vm => {54vm.user = user55vm.loading = false56})57})58.catch(error => {59next(vm => {60vm.error = error61vm.loading = false62})63})64}65}66```6768## Solution: Async beforeRouteEnter (Options API)6970```javascript71export default {72data() {73return { userData: null }74},7576async beforeRouteEnter(to, from, next) {77try {78const user = await fetchUser(to.params.id)7980// Still need callback for component access81next(vm => {82vm.userData = user83})84} catch (error) {85// Redirect on error86next('/error')87}88}89}90```9192## Composition API Alternative9394In Composition API with `<script setup>`, you cannot use `beforeRouteEnter` directly because the component instance is being set up. Use different patterns instead:9596```vue97<script setup>98import { ref, onMounted } from 'vue'99import { useRoute, onBeforeRouteUpdate } from 'vue-router'100101const route = useRoute()102const user = ref(null)103const loading = ref(true)104105// Option 1: Fetch in onMounted (after component exists)106onMounted(async () => {107user.value = await fetchUser(route.params.id)108loading.value = false109})110111// Option 2: Handle subsequent param changes112onBeforeRouteUpdate(async (to, from) => {113if (to.params.id !== from.params.id) {114loading.value = true115user.value = await fetchUser(to.params.id)116loading.value = false117}118})119</script>120```121122## Route-Level Data Fetching123124For data that should load BEFORE navigation, use route-level guards:125126```javascript127// router.js128const routes = [129{130path: '/users/:id',131component: () => import('./UserProfile.vue'),132beforeEnter: async (to, from) => {133try {134// Store data for component to access135const user = await fetchUser(to.params.id)136to.meta.user = user // Attach to route meta137} catch (error) {138return '/error'139}140}141}142]143```144145```vue146<!-- UserProfile.vue -->147<script setup>148import { useRoute } from 'vue-router'149150const route = useRoute()151// Access pre-fetched data from meta152const user = route.meta.user153</script>154```155156## Comparison of Navigation Guards157158| Guard | Has `this`/component? | Can delay navigation? | Use case |159|-------|----------------------|----------------------|----------|160| beforeRouteEnter | NO (use next callback) | YES | Pre-fetch, redirect if data missing |161| beforeRouteUpdate | YES | YES | React to param changes |162| beforeRouteLeave | YES | YES | Unsaved changes warning |163| Global beforeEach | NO | YES | Auth checks |164| Route beforeEnter | NO | YES | Route-specific validation |165166## Key Points1671681. **beforeRouteEnter runs before component creation** - No access to `this`1692. **Use next(vm => ...) callback** - Only way to access component instance1703. **Composition API has limitations** - Use onMounted or global guards instead1714. **Consider route meta for pre-fetched data** - Clean separation of concerns1725. **beforeRouteUpdate and beforeRouteLeave have component access** - They run when component exists173174## Reference175- [Vue Router In-Component Guards](https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards)176- [Vue Router Navigation Resolution Flow](https://router.vuejs.org/guide/advanced/navigation-guards.html#the-full-navigation-resolution-flow)177