一個被渲染組件同樣可以包含自己的嵌套 <router-view>。同樣要有vue-router的三個要素:路由map 、路由視圖、路由導航。
舉個在"/apple" 下再嵌套路由的例子。
要素一:路由map
子路由需要在 VRouter 的參數中使用 children 配置:
let router=new VRouter({ mode:'history', routes:[ { path:'/apple/:color', component:Apple, name: 'applename', children:[ { path:'red-apple', component:RedApple }, { path:'green-apple', component:GreenApple } ] }, { path:'/banana', name: 'banananame', component:Banana } ] });
要素二:路由視圖
在上級路由匹配組件里添加路由視圖,本例中在 Apple 組件的模板添加 <router-view>
<template> <div> <p>apple </p> <router-view></router-view> </div> </template>
要素三:路由導航
與頂級路由相似,可以使用<router-link> 創建 a 標簽來定義導航鏈接,也可以使用 router.push ()方法
<router-link :to="{path: '/apple/red-apple' }"> to red apple</router-link>
router.push({path:'/apple/red-apple'})
要注意,以 / 開頭的嵌套路徑會被當作根路徑。
更詳細的關於 <router-link :to="...">和 router.push(...)的知識總結在 Vue-詳解設置路由導航的兩種方法:<router-link :to="..."> 和router.push(...)