带有可选参数和任意顺序的 Vue.JS 路由

lut*_*ien 2 vue.js vue-router routeparams

我想在我的 Vue.JS 应用程序中使用vue-router这样的查询参数:

http://localhost:8080/#/home/name=Alice&surname=Smith
Run Code Online (Sandbox Code Playgroud)

我已将此路线添加到我的routesrouter.ts

 routes: [{
    path: '/home/name=:name&surname=:surname',
    name: 'home',
    component: Home
 }]
Run Code Online (Sandbox Code Playgroud)

我还想做以下两件事:

1)我希望能够有参数name,并surname以任意顺序。例如,这两个 URL 应该导致相同的视图:

http://localhost:8080/#/home/name=Alice&surname=Smith
http://localhost:8080/#/home/surname=Smith&name=Alice
Run Code Online (Sandbox Code Playgroud)

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

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

Max*_*nov 5

要实现您想要的,您必须更改路线:

routes: [{
    path: '/home',
    name: 'home',
    component: Home
}]
Run Code Online (Sandbox Code Playgroud)

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

router.push({ name: 'home', query: { name: 'Alice', surname: 'Smith' }});
Run Code Online (Sandbox Code Playgroud)

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

http://localhost:8080/#/home?name=Alice&surname=Smith
Run Code Online (Sandbox Code Playgroud)

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

查看文档以获取更多信息。