<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>嵌套router</title> <script src="./lib/vue-2.4.0.js"></script> <script src="./lib/vue-router-3.0.1.js"></script> </head> <body> <div class="container"> <!-- 符組件的連接指向了denglu路徑 --> <router-link to="/denglu">顯示</router-link> <router-view></router-view> </div> <template id="account"> <div> <h1>這個是一個組件</h1> <!-- 子組件的連接要指向denglu路徑下的longin路徑 --> <router-link to="/denglu/login">登錄</router-link> <router-link to="/denglu/zhuce">注冊</router-link> <router-view></router-view> </div> </template> <script> var box={ template:'#account' } var login={ template:'<h1>登錄</h1>' } var zhuce={ template:"<h1>注冊</h1>" } var router=new VueRouter({ routes: [ // 路由規則主路徑 指向了denglu 子路徑使用children 屬性, //實現子路由,同時,子路由的 path 前面,不要帶 / ,否則永遠以根路徑開始請求,這樣不方便我們用戶去理解URL地址 {path:'/denglu',component:box,children:[ {path:"login",component:login}, {path:"zhuce",component:zhuce}, ]}, ] }) var vm=new Vue({ el:".container", data:{}, router }) </script> </body> </html>
命名視圖(就是給router-view 添加一個name屬性)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> <script src="./lib/vue-router-3.0.1.js"></script> </head> <body> <div class="container"> <router-view name="header"></router-view> <div class="aa"> <router-view name="left"></router-view> <router-view name="mian"></router-view> </div> </div> <!-- 添加樣式 --> <style> .box{ padding: 0; margin: 0; } h1{ padding: 0; margin: 0; } .headerbox{ background-color: green; } .aa{ display: flex; height: 600px; } .leftbox{ flex:2; background-color: hotpink; } .mianbox{ flex:8; background-color: indigo; } </style> <script> var heaer={ template:"<h1 class='headerbox'>這是網頁的頭部</h1>" } var leftbox={ template:"<h1 class='leftbox'>這是網頁的側邊欄</h1>" } var mianbox={ template:"<h1 class='mianbox'>這是網頁的主體</h1>" } var router=new VueRouter({ routes: [ {path:'/',components:{ header:heaer, left:leftbox, mian:mianbox }} ] }) var vm=new Vue({ el:".container", data:{}, router:router }) </script> </body> </html>