在 vue 路由中匹配查询参数 [英] Matching query param in vue routes
问题描述
有没有办法通过查询参数进行路由?我想匹配以下路线:site.com/?foo=123
.我试过这样的事情
Is there any way to route by a query param? I would like to match the following route: site.com/?foo=123
. I've tried things like
{ path: '/\?foo=[\d]*' }
没有成功.
推荐答案
很遗憾,您无法匹配路由定义的 path
字符串中的查询参数.
Unfortunately, you can't match a query param in the path
string of a route definition.
Vue Router 使用 path-to-regexp
和 其文档 说:
Vue Router uses path-to-regexp
, and its documentation says:
path-to-regexp 返回的 RegExp 旨在与路径名或主机名一起使用.它无法处理 URL 的查询字符串或片段.
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.
<小时>
您可以使用正则表达式来匹配路由参数,方法是在参数名称后的括号中指定正则表达式,如下所示:
You can use regular expressions to match on a route param by specifying the regex in parenthesis after the param name like so:
{ path: '/:foo([\d]*)' },
但是,Vue Router 的路由参数不能在查询中.
But, Vue Router's route params can't be in the query.
以下是不同路由的一些示例- 匹配 Vue Router 提供的功能.
如果您确实需要检查 url 的查询,您可以使用 beforeEnter
处理程序手动匹配查询,如果格式不正确,则重新路由:
If you really need to check the query of the url, you could use the beforeEnter
handler to match the query manually and then reroute if it isn't the correct format:
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,
}];
这篇关于在 vue 路由中匹配查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!