在 vue 路由中匹配查询参数

Matching query param in vue routes

有什么方法可以通过查询参数进行路由吗?我想匹配以下路线:site.com/?foo=123。我尝试过

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

没有成功。

不幸的是,您无法匹配路由定义的 path 字符串中的查询参数。

Vue Router 使用 path-to-regexp,而 its documentation 表示:

The RegExp returned by path-to-regexp is intended for use with pathnames or hostnames. It can not handle the query strings or fragments of a 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,
}];