Matching query param in vue routes

流过昼夜 提交于 2021-02-19 01:29:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!