一、路由的三個要素
- 映射表窿吩,路由map
// index.js 文件
Vue.use(Router)
export default new Router({
mode: 'history', // 開始 HTML5 模式茎杂,自帶歷史記錄
routes: [
{
path: '/apple', // 路由
component: Apple // 組件,需import引入
},
{
path: '/banana',
component: Banana
}
]
})
- 展現(xiàn)位置,
<router-view>
通常配合<keep-alive>
做緩存
<keep-alive>
<router-view></router-view>
</keep-alive>
- 頁面中跳轉(zhuǎn)纫雁,不再使用
<a>
標(biāo)簽
<router-link :to="{path: '/apple'}">LinkToApple</router-link>
二煌往、路由參數(shù)
- 傳遞
routes: [
{
path: '/',
component: Hello
},
{
path: '/apple/:color/detail/:type', // 設(shè)置參數(shù)
component: Apple
}
]
http://localhost:8080/apple/green/detail/fruit
注:設(shè)置了參數(shù)后,則必須傳入?yún)?shù)轧邪,否則路由訪問失敗
- 接收
通過this.$route.params
來接收參數(shù)
<p>{{ $route.params.color }}</p>
<p>{{ $route.params.type }}</p>
...
console.log(this.$route.params)
三刽脖、路由嵌套
routes: [
{
path: '/',
component: Hello
},
{
path: '/apple',
component: Apple,
children: [ // 定義子路由
{
path: 'green',
component: GreenApple,
}
]
}
]
- 子路由只需再寫一個 children 數(shù)組
- 而接受子路由對應(yīng)的component需要在其分支根節(jié)點(diǎn)Apple 中使用
<router-view></router-view>
四、導(dǎo)航
- 聲明式導(dǎo)航忌愚,如
<router-link :to="{path: '/apple'}">LinkToApple</router-link>
- 編程式導(dǎo)航
router.push({path: 'apple'}) // 指定到特定的頁面
五曲管、 命名視圖
<router-view name="view-a"></router-view>
<router-view name="view-b"></router-view>
routes: [
{
path: '/',
component: {
viewA: Apple, // 將組件Apple 賦 viewA
viewB: RedApple // 將組件RedApple 賦 viewB
}
},
{
path: '/apple/:color/detail/:type', // 設(shè)置參數(shù)
component: Apple
}
]
六、 重定向
routes: [
{
path: '/',
redirect: '/apple' // 重定向到 /apple 路徑
}
{
path: '/apple', // 路由
component: Apple // 組件硕糊,需import引入
}
]