代码之家  ›  专栏  ›  技术社区  ›  luthien

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

  •  1
  • luthien  · 技术社区  · 6 年前

    vue-router 这样地:

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

    我已将此路线添加到 routes router.ts :

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

    另外,我还想做两件事:

    name surname 以任何顺序。 E、 g.这两个url应该导致相同的视图:

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

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

    有办法做这些事吗?谢谢您!

    1 回复  |  直到 6 年前
        1
  •  2
  •   Max Martynov    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

    检查 documentation 以获取更多信息。