Negotiating request parameter in vue routes

Is there a way to route by request parameter? I would like to follow the following route: site.com/?foo=123

. I have tried things like

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

      

without success.

+3


source to share


1 answer


Unfortunately, you cannot match the query parameter in the path

route definition string .

Vue Router uses path-to-regexp

, and its documentation says:

The RegExp returned by path-to-regexp is for use with pathnames or hostnames. It cannot handle query strings or URL fragments.


You can use regular expressions to match the route parameter by specifying the regular expression in parentheses after the parameter name like so:

{ path: '/:foo([\d]*)' },

      



But Vue Router request parameters cannot be in the request.

Below are examples of the different route negotiation features provided by Vue Router.


If you really need to validate the request for a url, you can use a handler beforeEnter

to match the request manually and then redirect if it is not 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,
}];

      

+3


source







All Articles