问题
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]*' }
without success.
回答1:
Unfortunately, you can't match a query param in the path
string of a route definition.
Vue Router uses path-to-regexp
, and its documentation says:
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]*)' },
But, Vue Router's route params can't be in the query.
Here are some examples of the different route-matching features Vue Router provides.
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,
}];
来源:https://stackoverflow.com/questions/44797824/matching-query-param-in-vue-routes