Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

vue-router如何忽略路由参数去匹配理由规则?

现在有一个需求,就是页面刷新的时候,我需要判断当前url是否在路由规则(集合)里面?如果存在,就定位到当前路由,否则跳转到首页。

假设当前路由为:/xxx/yyy/100

定义的路由里面有:/xxx/yyy/:id

刷新页面时,我需要使用/xxx/yyy/100匹配到/xxx/yyy/:id,这个时候我如何能够方便的忽略路由参数来比较呢?

自己方法如下:

let currentRoute = this.$route
let currentRoutePath = currentRoute.path.toLowerCase()
if(currentRoute.params) {
  for (const key in currentRoute.params) {
    if (currentRoute.params.hasOwnProperty(key)) {
      const element = currentRoute.params[key];
      currentRoutePath = currentRoutePath.replace(element, `:${key}`)
    }
  }
}

也就是把现有路由(赋值后)转成路由规则(赋值前),如:

当前路由
/xxx/yyy/ccc8a6d0-3e86-465e-a255-4bf4e3735b79
转成成
/xxx/yyy/:id

然后进行匹配,不知道时候有问题(还未经过长时间验证)。

有更好的方法吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

你可以直接在路由文件中,最后写上通配符*,捕获所有路由或 404 Not found 路由,路由匹配不到就会走这个通配路由,直接定位到首页不久可以了吗?

const HomeComponent = () => import('xxx')
{
    path: '*',
    component: HomeComponent
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...