一、Vue Router 的多級路由實現。
1.改寫路由配置,為需要添加多級路由的頁面,添加children屬性。
這里我們添加在Works 頁面里的。
// 配置路由 const router = new VueRouter({ routes:[ {path:'/',component:Home}, {path:'/works',component:Works,name:'WorksLink', //配置多級路由,在children數組里添加子路由信息 children:[ {path:'/work1',component:work1}, {path:'/work2',component:work2}, {path:'/work3',component:work3} ] }, {path:'/about',component:About}, {path:"*",redirect:'/'} //默認跳轉 ], mode:'history' })
2.在Works組件中引用並創建跳轉鏈接
<!-- 創建路由跳轉 --> <ul> <li><router-link to="work1">Work1</router-link></li> <li><router-link to="work2">Work2</router-link></li> <li><router-link to="work3">Work3</router-link></li> </ul> <!-- 引用路由 --> <router-view></router-view>
此時點擊鏈接進行跳轉,結果:
注意紅線處的地址!!!
此時我們的地址是采用 斜杠+地址 的形式。
當我們改寫成 直接 地址 的形式,看一下會有什么區別。
// 配置路由 const router = new VueRouter({ routes:[ {path:'/',component:Home}, {path:'/works',component:Works,name:'WorksLink', children:[ {path:'work1',component:work1}, {path:'work2',component:work2}, {path:'work3',component:work3} ] }, {path:'/about',component:About}, {path:"*",redirect:'/'} //默認跳轉 ], mode:'history' })
對應的組件中的跳轉也需要改變
<!-- 創建路由跳轉 --> <ul> <li><router-link to="/works/work1">Work1</router-link></li> <li><router-link to="/works/work2">Work2</router-link></li> <li><router-link to="/works/work3">Work3</router-link></li> </ul> <!-- 引用路由 --> <router-view></router-view>
觀察結果:
一個是直接在根路徑下跳轉,
一個則是父組件的路徑下。
具體喜歡哪一個,看自己,反正我覺得第二終好一點。
三級路由同理,繼續在跳轉的組件中添加children。。。
3.設置默認路由。
當我們跳到Works頁面時,如圖:
這里的沒有內容,必須等我們點擊Work1或works2,3才會顯示出來。
解決方法:
在父路由添加屬性 redirect :‘跳轉地址’,
// 配置路由 const router = new VueRouter({ routes:[ {path:'/',component:Home}, {path:'/works',component:Works,name:'WorksLink', redirect:'works/work1',//添加該屬性 children:[ {path:'work1',component:work1}, {path:'work2',component:work2}, {path:'work3',component:work3} ] }, {path:'/about',component:About}, {path:"*",redirect:'/'} //默認跳轉 ], mode:'history' })
這樣跳轉到Works頁面就會直接加載work1。
二、嵌套命名視圖,了解一下。
現在我們想在Home中把Works中的三個works加載出來,通過路由。
實現方法:
// 配置路由 const router = new VueRouter({ routes:[ {path:'/', components:{ //嵌套命名,將component加s default為默認路由 default:Home, theWork1:work1, theWork2:work2, theWork3:work3 }}, {path:'/works',component:Works,name:'WorksLink',redirect:'works/work1', children:[ {path:'work1',component:work1}, {path:'work2',component:work2}, {path:'work3',component:work3} ] }, {path:'/about',component:About}, {path:"*",redirect:'/'} //默認跳轉 ], mode:'history' })
這里我們在Home的子組件中進行引用:
卻發現頁面無法加載該引用!!!
<template> <div> <h1>Hello World</h1> <router-view name="theWork1"></router-view> <router-view name="theWork2"></router-view> <router-view name="theWork3"></router-view> </div> </template>
但是在根組件app.vue中,可以。
原因:不明,如果你知道,請一定告訴我。
(官方文檔也是一筆帶過,無語...)
三、滾動行為
注意: 這個功能只在支持 history.pushState
的瀏覽器中可用。
具體還是看 官方文檔 吧!