【问题标题】:Matching query param in vue routes在 vue 路由中匹配查询参数
【发布时间】:2017-12-01 13:01:50
【问题描述】:

有没有办法通过查询参数进行路由?我想匹配以下路线:site.com/?foo=123。我尝试过类似

{ path: '/\?foo=[\d]*' }

没有成功。

【问题讨论】:

  • 你可以在调用$router.push时传递一个query对象。你是这个意思吗?或者您能否更清楚地描述预期的行为以及什么不起作用?
  • @thanksd 不,我不是这个意思。我想根据查询字符串参数匹配路由,而不是像/:id 这样的“常规” id,我需要像/\?id=[\d]* 这样的东西来匹配/?id=123

标签: javascript vue.js vue-router


【解决方案1】:

很遗憾,您无法匹配路由定义的path 字符串中的查询参数。

Vue 路由器使用path-to-regexp,而its documentation 表示:

path-to-regexp 返回的 RegExp 旨在与路径名或主机名一起使用。它无法处理 URL 的查询字符串或片段。


可以使用正则表达式来匹配路由参数,方法是在参数名称后的括号中指定正则表达式,如下所示:

{ path: '/:foo([\d]*)' },

但是,Vue Router 的路由参数不能在查询中。

Here are some examples of the different route-matching features Vue Router provides.


如果您确实需要检查 url 的查询,您可以使用 beforeEnter 处理程序手动匹配查询,然后如果格式不正确则重新路由:

const routes = [{
  name: 'home',
  path: '/',
  component: Home,
  beforeEnter(to, from, next) {
    if (to.query.foo && to.query.foo.match(/[\d]*/)) {
      next({ name: 'foo', query: to.query });
    } else {
      next();
    }
  }
}, {
  name: 'foo',
  path: '/',
  component: Foo,
}];

【讨论】:

  • 您给出的正则表达式“参数名称后的括号”示例将使路由器使用该路由作为根路径。虽然超级接近工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-07
  • 2021-04-27
  • 1970-01-01
  • 2017-09-11
  • 2013-11-26
  • 1970-01-01
  • 2017-06-22
相关资源
最近更新 更多