我想在我的 Vue.JS 应用程序中使用 vue-router
查询参数,如下所示:
http://localhost:8080/#/home/name=Alice&surname=Smith
我已将此路由添加到 router.ts
中的 routes
:
routes: [{
path: '/home/name=:name&surname=:surname',
name: 'home',
component: Home
}]
我还想做以下两件事:
1) 我希望能够以任何顺序使用参数 name
和 surname
。
例如。这两个 URL 应该指向相同的 View :
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' }});
url 将是(url 中查询键的顺序无关紧要):
http://localhost:8080/#/home?name=Alice&surname=Smith
在路由中,您可以获得查询参数作为 this.$route.query.name
& this.$route.query.surname
。
检查 documentation获取更多信息。
关于具有可选参数和任意顺序的 Vue.JS 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51787164/