Skip to content

Get resolved route route provided in <RouterView> with new useLocalRoute() #2673

@pieczorx

Description

@pieczorx

Reproduction

Click

Steps to reproduce the bug

  1. Pass route prop to <RouterView> like this:
<RouterView :route="route1"></RouterView>
  1. Go to page that route2 resolves to, for example /route-2
  2. print useRoute() somewhere in a component thatroute1 will resolve to.

Expected behavior

We should see information about route1

Actual behavior

We see information about route2

Additional information

As described in RFC we should properly inject that route into all children:

Internally, router-view must make sure its children (nested views) use that same location to be consistent. In v4, using inject/provide should make this simple, in v3, we might need to look up like we do for depth. If a route prop is provided, it takes precedence against any providen route on the router-view receiving the prop and all its children.

Current workaround is to create new composable, something like this:

import {inject, Ref, computed, unref} from 'vue'
import {useRoute, routerViewLocationKey, RouteLocationNormalized} from 'vue-router'

export function useLocalRoute() {
  const globalRoute = useRoute()
  const routerViewRouteRef = inject<Ref<RouteLocationNormalized>>(routerViewLocationKey, null)
  const route = computed<RouteLocationNormalized>(() => routerViewRouteRef ? unref(routerViewRouteRef) : globalRoute)
  return route
}

And then use it like this

const route = useLocalRoute()

 

Metadata

Metadata

Assignees

No one assigned

    Labels

    ⚡️ enhancementimprovement over an existing feature

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions