【问题标题】:How to load different component if route has params using VueJS Router如果路由具有使用 VueJS 路由器的参数,如何加载不同的组件
【发布时间】:2019-01-27 10:18:46
【问题描述】:

如果路由中包含任何道具,我正在寻找一种适当的方法来加载不同的 VueJS 组件。

例如,如果我去

/用户

我得到用户列表页面,如果我想去

/users/1

我会去用户个人资料页面。

我一直在尝试添加另一个带有参数的子路由,但它似乎无济于事:

{
            path: "users",
            name: "users",
            component: UsersList,
            children: [
                {
                    path: "users/:userId",
                    name: "User Profile",
                    component: UserProfile,
                },
            ]
},

我正在通过这样的方法推送用户配置文件路由:

this.$router.push({ path: 'users', name: 'User Profile', query: { userId: row.id }})

有什么想法吗?

【问题讨论】:

    标签: vue.js vuejs2 vue-component vue-router


    【解决方案1】:

    这很简单。这是你需要做的:

    {
        path: "users",
        name: "users",
        // IMPORTANT - UserParent contains `<router-view></router-view>`
        component: UserParent,
        children: [
            {
                // IMPORTANT - NEEDS TO BE BLANK
                path: "",
                name: "user-list",
                component: UserList,
            },
    
            {
                path: ":userId",
                name: "user-profile",
                component: UserProfile,
            }
        ]
    }
    

    这里的路线将被连接起来形成最终路线。

    【讨论】:

    • 谢谢,这可行,但访问用户配置文件路由时的 URL 已从 /users 更改为 /?userId=9,我希望保留 /users。有什么方法可以实现吗?
    • @butaminas,您在路由中使用查询参数,如下所示:query: { userId: row.id }。不要那样做。使用:this.$router.push({ path: 'users', name: 'User Profile', params: { userId: row.id }}。你应该使用params 而不是query
    • 谢谢!这是主要问题!另外,为了不需要使用父组件,我将 user-profile 路由移出子组件并将路径更改为 users/:userID 以达到相同的结果。
    • @butaminas,虽然它会起作用,但是当你想同时激活两个视图时应该使用它。使用您的路由配置,UserList 和 UserProfile 组件都将处于活动状态。这就是它创造的印象。当然,有办法。但那是你真正需要的吗?更喜欢干净的路由结构。从长远来看,它会有所帮助。
    • 在这种特殊情况下,user-profile route 用作模式的替代方案。完成对用户的编辑后,您将返回user-list 路由,除了首先转到user-list 路由之外,没有其他方法可以到达user-profile 路由。我确实同意,从长远来看,将 user-profile 路由作为子路由更有意义,但如果它是一个非常小的应用程序,创建父组件就像拥有额外的路由一样不干净。不过会试验这两种情况。谢谢!
    猜你喜欢
    • 2018-02-10
    • 2021-04-17
    • 2022-01-18
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 2021-01-16
    • 2019-12-10
    相关资源
    最近更新 更多