如何与Vue-Router一起使用组件 - 纽约



我对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相关的页面具有蓝色背景),所以我想以某种方式创建一个"父"组件所有"孩子"组件都一样。类似:

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组件 - 我希望它作为一个包装器"嵌套组件。

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

我解决此问题的方式是使用基本路径重定向。

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

在您的情况下,它将是

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

这确保

最新更新