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

标签 vue.js vue-router routeparams

我想在我的 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) 我希望能够以任何顺序使用参数 namesurname。 例如。这两个 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/

相关文章:

javascript - 如何在 vuejs 中用新数据刷新数据表?

javascript - Vue 获取发布数据到 Controller asp.net mvc

javascript - Vue Js - 通过 v-for X 次循环(在一个范围内)

javascript - 仅保护命名 View 路由器下的一个组件 - Vue js

express - 在 Express 上使用带有 `app.use` 的路由参数

javascript - 如何在Vue js中的v-for循环中使用v-model

vue.js - 路由器级别的 Vue 3 动态组件

javascript - 在 vue.js 、 vue-router 和 webpack 中加载静态 html 文件

mocking - Postman Mock 服务器路由参数