Vue-router: [Feature] Expose parent route for subroute

Created on 4 Nov 2015  路  5Comments  路  Source: vuejs/vue-router

It would be very nice to have the parent route exposed into route object for subroutes.

Common use case is allowing to route to parent route (on validation by example) without using history.back() which is a different case.

It would be even better if route vm is exposed into the route object so we can write:

data() {
   this.something = this.$route.$parent.vm.something;
}
feature request

Most helpful comment

Yest, it can be solved with named routes but it is a burden to maintain it manually. The $parent would allow for implementation of a back button that goes one level up in the hierarchy or simple breadcrumbs. It would be awesome to have.

Is there any option to revisit this?

P.S. Since we have access to the $parent on the Vue instance, it would be only logical to have it here as well.

All 5 comments

I think the first use case can be solved with named routes; the second use case sounds like a bad idea (directly accessing parent data from child views) - instead it's probably better to pass down data explicitly using props, or using some global state management pattern.

Yest, it can be solved with named routes but it is a burden to maintain it manually. The $parent would allow for implementation of a back button that goes one level up in the hierarchy or simple breadcrumbs. It would be awesome to have.

Is there any option to revisit this?

P.S. Since we have access to the $parent on the Vue instance, it would be only logical to have it here as well.

+1, have same need for somewhat complex app gathering routes from separate packages.

The $parent would allow for implementation of a back button that goes one level up in the hierarchy or simple breadcrumbs. It would be awesome to have.

For those coming up against this, I'm solving it thus:

From: https://router.vuejs.org/api/#the-route-object (scroll to $route#matched

An Array containing route records for all nested path segments of the current route. Route records are the copies of the objects in the routes configuration Array (and in children Arrays):

The $route has a matched property which is an array of route matches (tree-like) with the current route being at the end of the array and thus the parent being second-last element in the array.

So to get any route's parent (better check if it has a parent by length >= 2 ... ?)
this.$route.matched.slice(-2).shift()

Because, per the docs, the element is a 'route record' - it contains name, params, query, meta, etc.

Was this page helpful?
0 / 5 - 0 ratings