【问题标题】:vue-router: how to check if current route is a route or one of its subroutes?vue-router:如何检查当前路由是路由还是其子路由之一?
【发布时间】:2019-10-18 20:57:09
【问题描述】:

我正在包装 router-link 以添加一些功能。

我需要检查当前路线是路线还是路线的子路线。

类似如下

我知道它不能工作,因为 :active 需要一个布尔值,但是 javascript String.match 返回一个数组;:这是为了解释我的目标

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

在我的 router.js 中,我定义了 /customer/{customer_id}/users 被命名为 customer_users 并且 /customer/{customer_id}/users/{user_id} 被命名为 customer_users_edit

所以我希望能够在我的包装器中为这两条路线设置 ":active"。

【问题讨论】:

  • 你不能在那里写一个布尔表达式吗?类似$route.name.match('customer_users*').length()>0
  • 是和否,因为我还需要在检查其长度之前检查匹配是否为空
  • 仅供参考,您正在寻找的正则表达式方法是RegExp.prototype.test(),例如/^customer_users.*/.test($route.name),但有更好的方法来做到这一点

标签: vue.js vue-router


【解决方案1】:

使用$route.matched 属性查看当前路由是您的customer_users 还是它的任何子级。

例如,使用Array.prototype.some()

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

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

$route.matched

输入:Array<RouteRecord>

一个数组,包含当前路由的所有嵌套路径段的路由记录

【讨论】:

    猜你喜欢
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2019-08-26
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多