Skip to content
Advertisement

How to inherit props from parent route with vue-router

I have the following router configuration and would like that the id of the main.parent route is converted to an integer and then passed into the child components (given props: true) for all child components.

JavaScript

However, it seems as if the route function is only really called once (when evaluating /:id) and not when /:id/details is evaluated. The relevant code in vue-router seems to confirm this.

JavaScript

I wonder if anyone tried to solve the same problem and what they came up with a solution. Ideally, I’d like to avoid duplicating the props function for every child route.

Advertisement

Answer

There’s no such feature in Vue Router for passing props to child routes that way.

Instead, you could use provide/inject to effectively do this. The parent would provide the id property, and any descendant could inject it:

  1. In ParentComponent.vue, use toRefs() on props to get a reactive ref to the id prop.
  2. Use provide() to provide that id to any children (including child routes).
  3. Apply a key on <router-view> to ensure the view is re-rendered based on the unique id.
  4. In ChildComponent.vue, use the inject prop to inject the id from step 2.
JavaScript
JavaScript

Composition API demo

Options API demo

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement