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

问题描述 投票:0回答:2

我想在我的 Vue.JS 应用程序中使用

vue-router
来查询参数,如下所示:

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

我已将此路线添加到我的

routes
中的
router.ts
:

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

我还想做以下两件事:

1)我希望能够以任意顺序拥有参数

name
surname
。 例如。这两个 URL 应导致相同的视图:

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

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

有办法做到这些事情吗?谢谢!

vue.js vue-router routeparams
2个回答
6
投票

要实现你想要的,你必须改变路线:

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

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

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

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

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

在路线内部,您可以获取查询参数为

this.$route.query.name
&
this.$route.query.surname

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


0
投票

如果您想在路由器链接中使用用户,请使用此

<router-link v-bind:to="{path:'/home' ,query: { name: 'helo' }}">home</router-link>"

然后使用

this.$route.query.name

得到这个
© www.soinside.com 2019 - 2024. All rights reserved.