首页 文章

如何使用vue-router组件嵌套?

提问于
浏览
1

我对Vue很新,我找不到如何使用嵌套组件和vue-router的好方法 .

到目前为止我所拥有的(省略了一些不重要的代码):

的index.html

<body>
    <div id="app">
        <router-view></router-view>
    </div>

app.js

const router = new VueRouter({
    routes: [{ path: '/login', component: Login }]
})

const app = new Vue({
    router,
}).$mount('#app')

组件/ Login.vue

<template>
    <h1>Please log in</h1>
</template>

这非常有效 - 我导航到 /login 并在 h1 标签中显示了该消息 . 如果我创建更多组件,如 RegisterResetPassword 并将它们添加到路由器,它仍然可以正常工作 . 但问题是这些组件中有一些重复的代码(例如,我希望所有与auth相关的页面都有蓝色背景)所以我想以某种方式创建一个"parent"组件,它将定义相同的东西所有"children"组件 . 就像是:

Auth component (makes the page-background blue)
    -> Login component (shows the login form)
    -> Register component (shows the registration form)

我知道我可以通过路线的“孩子”来做到这一点:

const router = new VueRouter({
    routes: [
        { path: '/', component: Auth, children: [
            { path: '/login', component: Login }
            { path: '/register', component: Register }
        ]}
    ]
})

但是使用这个配置,主路径 path: '/' ,这是完全错误的 - 我不希望 Auth 组件被使用"standalone" - 我希望它只是作为嵌套组件的"wrapper" .

解决这个问题的最佳方法是什么?

1 回答

  • 1

    我解决这个问题的方法是使用基本路径重定向 .

    { path: '', redirect: '/to/path' },
    

    在你的情况下,它会

    const router = new VueRouter({
        routes: [
            {
                path: '/',
                component: Auth,
                children: [
                    { path: '', redirect: '/login' },
                    { path: '/login', component: Login },
                    { path: '/register', component: Register }
                ]
            }
        ]
    })
    

    这确保了

相关问题