Vue.JS路由,带有可选参数,且顺序任意

时间:2018-08-10 13:00:58

标签: vue.js vue-router routeparams

我想使用vue-router在Vue.JS应用程序中使用查询参数,如下所示:

http://localhost:8080/#/home/name=Alice&surname=Smith

我已将此路线添加到routes中的router.ts

 routes: [{
    path: '/home/name=:name&surname=:surname',
    name: 'home',
    component: Home
 }]

我还想做以下两件事:

1)我希望能够以任意顺序使用参数namesurname。 例如。这两个网址应导致相同的视图:

http://localhost:8080/#/home/name=Alice&surname=Smith
http://localhost:8080/#/home/surname=Smith&name=Alice

2)我也希望它们是可选的。

有没有办法做这些事情?谢谢!

1 个答案:

答案 0 :(得分:2)

要实现所需的功能,您必须更改路线:

routes: [{
    path: '/home',
    name: 'home',
    component: Home
}]

使用查询参数打开此路线:

router.push({ name: 'home', query: { name: 'Alice', surname: 'Smith' }});

URL将是(URL中查询键的顺序无关紧要):

http://localhost:8080/#/home?name=Alice&surname=Smith

在路线内,您可以将查询参数设为this.$route.query.namethis.$route.query.surname

选中documentation以获得更多信息。