Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching query param in vue routes

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.

like image 275
Johan Avatar asked Jun 28 '17 08:06

Johan


People also ask

How to get parameter from URL in vue router?

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.

How to access the query params data inside Vue components?

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.

How to map two URLs to the same route in Vue?

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.

How do I use routes with params?

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.


1 Answers

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,
}];
like image 188
thanksd Avatar answered Sep 21 '22 01:09

thanksd