realtebo
realtebo

Reputation: 25699

vue-router: how to check if current route is a route or one of its subroutes?

I'm wrapping router-link to add some features.

I need to check if current route is a route or a subdolder of a route.

Something like the following

I know it cannot works, because :active need a boolean, but javascript String.match returns an array;: it's to explain my goal

:active="$route.name.match('customer_users*')"

In my router.js I definied that /customer/{customer_id}/users is named customer_users and that /customer/{customer_id}/users/{user_id} is named customer_users_edit.

So i'd like to be able to set ":active" in my wrapper for both these routes.

Upvotes: 25

Views: 36271

Answers (2)

Andy
Andy

Reputation: 127

I like the following for matching multiple routes:

import { useRoute } from 'vue-router'

if(route.matched.some(({ path }) => path.startsWith('/redirect'))){
    //handle redirect
}

You are checking if the current path

Upvotes: 0

Phil
Phil

Reputation: 165062

Use the $route.matched property to see if the current route is your customer_users or any of its children.

For example, using Array.prototype.some()

:active="$route.matched.some(({ name }) => name === 'customer_users')"

See https://v3.router.vuejs.org/api/#route-object-properties

$route.matched

type: Array<RouteRecord>

An Array containing route records for all nested path segments of the current route.

Upvotes: 40

Related Questions