2017-09-15 69 views
0

我是Vue的新手,我無法找到一個很好的方式來與vue-router一起使用嵌套組件。如何使用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') 

組件/登錄.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組件被「獨立」使用 - 我希望它僅僅作爲嵌套組件的「包裝器」。

解決此問題的最佳方法是什麼?

回答

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 } 
      ] 
     } 
    ] 
}) 

這確保了

+0

如果我想窩另一種觀點爲寄存器組件的子?使用相同的方法,它爲我顯示白色屏幕 –