我想在我的 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)我也希望它们是可选的。
有办法做到这些事情吗?谢谢!
要实现你想要的,你必须改变路线:
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
。
查看文档以获取更多信息。
如果您想在路由器链接中使用用户,请使用此
<router-link v-bind:to="{path:'/home' ,query: { name: 'helo' }}">home</router-link>"
然后使用
this.$route.query.name
得到这个