Skip to content

Expose the matched route record (route.matched[viewDepth]) #1408

Open
@posva

Description

@posva

When dealing with nested routes, it is often useful to access information relative to a specific route record:

const routes = [
  { path: '/', meta: { title: 'Parent' }, component: Parent, children: [
    { path: 'child', meta: { title: 'Child' }, component Child }
  ]}
]

In this scenario, when visiting /child, useRoute().meta.title will be "Child" everywhere in the app. But sometimes we need to get access to the relative information within the Parent and Child component. The question is is there anything else needed from route records besides meta?

To currently access this information, we need to index the route.matched array with the depth of the current view. Usually, you know this information within the component (as a hardcoded number) but that's not always the case, so we can instead inject the depth of the current view with viewDepthKey (https://github.com/vuejs/router/blob/main/src/index.ts#L29) or directly the matchedRouteKey with something like:

import { matchedRouteKey } from 'vue-router'

export function useMatchedRoute() {
  return inject(matchedRouteKey)!
}

This could also be exposed directly in <RouterView>s slot:

<RouterView v-slot="{ matchedRoute, Component }">
  <component :is="Component" :some-prop="matchedRoute.meta.something" />
</RouterView>
  • Could this create unexpected re-render issues?
  • Should we expose meta directly instead?

From

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestneeds RFCThis feature needs to go through the RFC process first

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions