配置
如果在一個模塊化工程中使用它,必須要通過Vue.use()明確地安裝路由功能:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
基礎(chǔ)
Getting Started
HTML
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 組件來導(dǎo)航. -->
<!-- 通過傳入 `to` 屬性指定鏈接. -->
<!-- <router-link> 默認(rèn)會被渲染成一個 `<a>` 標(biāo)簽 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的組件將渲染在這里 -->
<router-view></router-view>
</div>
javaScript
// 0. 如果使用模塊化機制編程,導(dǎo)入Vue和VueRouter,要調(diào)用 Vue.use(VueRouter)
// 1. 定義(路由)組件。
// 可以從其他文件 import 進來
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定義路由
// 每個路由應(yīng)該映射一個組件。 其中"component" 可以是
// 通過 Vue.extend() 創(chuàng)建的組件構(gòu)造器,
// 或者,只是一個組件配置對象。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 創(chuàng)建 router 實例,然后傳 `routes` 配置
const router = new VueRouter({
routes // (縮寫)相當(dāng)于 routes: routes
})
// 4. 創(chuàng)建和掛載根實例。
// 記得要通過 router 配置參數(shù)注入路由,
// 從而讓整個應(yīng)用都有路由功能
const app = new Vue({
router
}).$mount('#app')
// 現(xiàn)在,應(yīng)用已經(jīng)啟動了!
動態(tài)路由匹配
通俗的講就是,路徑中包含參數(shù),而對應(yīng)的組件是一定的。在線例子
響應(yīng)路由參數(shù)的變化
當(dāng)使用路由參數(shù)時,原來的組件實例會被復(fù)用,組件的生命周期鉤子不會再被調(diào)用。
因為兩個路由都渲染同個組件,比起銷毀再創(chuàng)建,復(fù)用顯得更加高效。
復(fù)用組件時,想對路由參數(shù)的變化做出響應(yīng)的話,你可以簡單的watch(檢測變化) $route對象
const User = {
template: '...',
watch: {
'$route' (to, from) {
// 對路由變化做出響應(yīng)
}
}
}
嵌套路由
<router-view>中的組件還可以包含自己的<router-view>在線例子

上圖中的嵌套結(jié)構(gòu)如下所示,B1和B2就是B的子結(jié)構(gòu),在路由中通過children配置。
- A
| --- B
| | ------B1
| | ------B2
| --- C
編程式導(dǎo)航
導(dǎo)航的兩種方式
- <router-link>創(chuàng)建a標(biāo)簽
- router的實例方法
| 方法 | 功能 |
|---|---|
| router.push(location) | 向history棧添加新的記錄 |
| router.replace(location) | 替換當(dāng)前的history記錄 |
| router.go(n) | 在history記錄中向前后者后退多少步 |
命名路由
通過名稱標(biāo)識路由。
創(chuàng)建Router實例的時候,在routes配置中給某個路由設(shè)置名稱(name)。
命名視圖
界面中可以擁有多個單獨命名的視圖,而不是只有一個單獨的出口(<router-view>)
如果router-view沒有設(shè)置名字,那么默認(rèn)為default。
進階
導(dǎo)航鉤子
導(dǎo)航表示路由正在發(fā)生改變。vue-router提供的導(dǎo)航鉤子主要用來攔截導(dǎo)航,讓它完成跳轉(zhuǎn)或取消。
全局鉤子
| 鉤子 | 用法 |
|---|---|
| router.beforeEach() | 導(dǎo)航之前調(diào)用 |
| router.afterEach() | 導(dǎo)航之后調(diào)用,不能改變導(dǎo)航 |
路由獨享的鉤子
| 鉤子 | 用法 |
|---|---|
| router.beforeEnter() | 進入此導(dǎo)航 |
組件內(nèi)的鉤子
| 鉤子 | 用法 |
|---|---|
| router.beforeRouteEnter() | 在渲染該組件的對應(yīng)路由被confirm前調(diào)用。 不能獲取組件實例this,因為當(dāng)鉤子執(zhí)行前,組件實例還沒被創(chuàng)建 |
| router.beforeRouteUpdate() | 在當(dāng)前路由改變,但是該組件被復(fù)用時調(diào)用。 |
| router.beforeRouteLeave() | 導(dǎo)航離開該組件的對應(yīng)路由時調(diào)用。 |
路由元信息
定義路由的時候可以配置meta字段
通過$route.matched數(shù)組來檢查路由記錄中的meta字段。
to.matched.some()
過渡動效
所有路由
<transition>
<router-view></router-view>
</transition>
單個路由
在路由組件內(nèi)使用<transition>并設(shè)置不同的name
基于路由的動態(tài)過渡