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.
The Vue router gives us access to the $route instance object. On this object is the params property that we can use to access the parameter from the URL. The property name has to be the same as the one we define in the route path.
In programatic navigation, we can pass query params using this.$router.push () method. To access the query params data inside vue components we need to use the $route object. Inside component <script> tag we need to use this.$route instead of $route.
In Vue Router we can use a dynamic segment in the path to achieve that, we call that a param: Now URLs like /users/johnny and /users/jolyne will both map to the same route.
A working demo of this example can be found here. One thing to note when using routes with params is that when the user navigates from /users/johnny to /users/jolyne, the same component instance will be reused. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one.
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,
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With