如何在 vue-router 中使用组件嵌套?
How to use component-nesting with 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')
components/Login.vue
<template>
<h1>Please log in</h1>
</template>
这非常有效 - 我导航到 /login
,它向我显示了 h1
标记中的消息。如果我创建更多组件,如 Register
或 ResetPassword
并将它们添加到路由器,它仍然可以正常工作。但问题是这些组件中有一些重复代码(例如,我希望所有与身份验证相关的页面都有蓝色背景)所以我想以某种方式创建一个 "parent" 组件,它会定义东西这对于所有 "children" 组件都是相同的。类似于:
Auth component (makes the page-background blue)
-> Login component (shows the login form)
-> Register component (shows the registration form)
我知道我可以通过路线 "children":
const router = new VueRouter({
routes: [
{ path: '/', component: Auth, children: [
{ path: '/login', component: Login }
{ path: '/register', component: Register }
]}
]
})
但是有了这个配置,就有了主路由path: '/'
,这是完全错误的-我不想在这里-我不想使用Auth
组件"standalone" - 我想要它作为嵌套组件的 "wrapper"。
解决这个问题的最佳方法是什么?
我解决这个问题的方法是使用基本路径重定向。
{ path: '', redirect: '/to/path' },
你的情况是
const router = new VueRouter({
routes: [
{
path: '/',
component: Auth,
children: [
{ path: '', redirect: '/login' },
{ path: '/login', component: Login },
{ path: '/register', component: Register }
]
}
]
})
这确保了
我是 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')
components/Login.vue
<template>
<h1>Please log in</h1>
</template>
这非常有效 - 我导航到 /login
,它向我显示了 h1
标记中的消息。如果我创建更多组件,如 Register
或 ResetPassword
并将它们添加到路由器,它仍然可以正常工作。但问题是这些组件中有一些重复代码(例如,我希望所有与身份验证相关的页面都有蓝色背景)所以我想以某种方式创建一个 "parent" 组件,它会定义东西这对于所有 "children" 组件都是相同的。类似于:
Auth component (makes the page-background blue)
-> Login component (shows the login form)
-> Register component (shows the registration form)
我知道我可以通过路线 "children":
const router = new VueRouter({
routes: [
{ path: '/', component: Auth, children: [
{ path: '/login', component: Login }
{ path: '/register', component: Register }
]}
]
})
但是有了这个配置,就有了主路由path: '/'
,这是完全错误的-我不想在这里-我不想使用Auth
组件"standalone" - 我想要它作为嵌套组件的 "wrapper"。
解决这个问题的最佳方法是什么?
我解决这个问题的方法是使用基本路径重定向。
{ path: '', redirect: '/to/path' },
你的情况是
const router = new VueRouter({
routes: [
{
path: '/',
component: Auth,
children: [
{ path: '', redirect: '/login' },
{ path: '/login', component: Login },
{ path: '/register', component: Register }
]
}
]
})
这确保了