Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skeith22's avatar

Is there a way to trigger beforeRouteEnter & beforeRouteUpdate on a child components?

Has anyone been successful of doing this?

I wanted to use both beforeRouteEnter and beforeRouteUpdate on the child component, so I would not have to write OR copy/paste the codes on the other index files, cause they're all similar.

so I wanted to make it a component that will be reusable by other Index files.

0 likes
2 replies
LaryAI's avatar
Level 58

Certainly! In Vue Router (both v2 and v3), the navigation guards beforeRouteEnter and beforeRouteUpdate can be defined in any component that is rendered by the router-view, including child components. However, there are a few caveats and best practices for making this reusable.

Key Points

  • Child components that are directly rendered by <router-view> can use beforeRouteEnter and beforeRouteUpdate.
  • Nested child components (not directly rendered by <router-view>) will not have these hooks called automatically.
  • To make this logic reusable, you can use a mixins or a base component.

Example: Using a Mixin

Create a mixin with your navigation guard logic:

// route-guard-mixin.js
export default {
  beforeRouteEnter(to, from, next) {
    // Your logic here
    next();
  },
  beforeRouteUpdate(to, from, next) {
    // Your logic here
    next();
  }
}

Then, in your child component:

import RouteGuardMixin from './route-guard-mixin';

export default {
  mixins: [RouteGuardMixin],
  // ...other component options
}

Example: Using a Base Component

Alternatively, create a base component:

// BaseRouteGuard.vue
<script>
export default {
  beforeRouteEnter(to, from, next) {
    // Your logic here
    next();
  },
  beforeRouteUpdate(to, from, next) {
    // Your logic here
    next();
  }
}
</script>

Then extend it:

<script>
import BaseRouteGuard from './BaseRouteGuard.vue';

export default {
  extends: BaseRouteGuard,
  // ...other component options
}
</script>

Important Note

If your child component is not directly rendered by <router-view>, these hooks won't be called. In that case, you can:

  • Move the logic to the parent component that is rendered by <router-view>.
  • Or, use a watcher on $route in the child component:
watch: {
  $route(to, from) {
    // Your logic here
  }
}

Summary

  • Use mixins or base components to reuse navigation guard logic.
  • Only components rendered by <router-view> get navigation guards called automatically.
  • For deeper child components, use a $route watcher.

Let me know if you need a more specific example based on your component structure!

skeith22's avatar

Mixins and Extends doesn't work on Route Guards

Please or to participate in this conversation.