安裝
直接下載
在Vue后面加載vue-router,它會自動安裝的:
<script src="/path/to/vue.js"></script>
<script src="/path/to/vue-router.js"></script>
NPM
npm install vue-router
如果在一個模塊化工程中使用它,必須要通過Vue.use()明確地安裝路由功能:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
如果使用全局的script標簽,則無須如此 (手動安裝)。
介紹
Vue Router是Vue.js官方的路由管理器。它和Vue.js的核心深度集成,讓構(gòu)建單頁面應(yīng)用變得易如反掌。包含的功能有:
- 嵌套的路由/視圖表
- 模塊化的、基于組件的路由配置
- 路由參數(shù)、查詢、通配符
- 基于Vue.js過渡系統(tǒng)的視圖過渡效果
- 細粒度的導(dǎo)航控制
- 帶有自動激活的CSS
class的鏈接 - HTML5歷史模式或
hash模式,在IE9中自動降級 - 自定義的滾動條行為
起步
用Vue.js + Vue Router創(chuàng)建單頁應(yīng)用,是非常簡單的。使用Vue.js,我們已經(jīng)可以通過組合組件來組成應(yīng)用程序,當(dāng)你要把Vue Router添加進來,我們需要做的是,將組件 (components) 映射到路由 (routes),然后告訴Vue Router在哪里渲染它們。下面是個基本例子:
<script src="path/.../to/vue/dist/vue.js"></script>
<script src="path/.../to/vue-router/dist/vue-router.js"></script>
<div id="app">
<h1>Hello App!</h1>
<p>
<!--使用router-link組件來導(dǎo)航-->
<!--通過傳入to屬性指定鏈接-->
<!--<router-link>默認會被渲染成一個<a>標-->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的組件將渲染在這里 -->
<router-view></router-view>
</div>
// 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配置
// 你還可以傳別的配置參數(shù)
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)啟動了!
通過注入路由器,我們可以在任何組件內(nèi)通過this.$router訪問路由器,也可以通過this.$route訪問當(dāng)前路由:
// Home.vue
export default {
computed: {
username () {
return this.$route.params.username
}
},
methods: {
goBack () {
window.history.length > 1
? this.$router.go(-1)
: this.$router.push('/')
}
}
}
當(dāng)<router-link>對應(yīng)的路由匹配成功,將自動設(shè)置class屬性值.router-link-active。
動態(tài)路由匹配
我們經(jīng)常需要把某種模式匹配到的所有路由,全都映射到同個組件。例如,我們有一個User組件,對于所有ID各不相同的用戶,都要使用這個組件來渲染。那么,我們可以在vue-router的路由路徑中使用動態(tài)路徑參數(shù)來達到這個效果。
const User = {
template: '<div>User</div>'
}
const router = new VueRouter({
routes: [
// 動態(tài)路徑參數(shù) 以冒號開頭
{ path: '/user/:id', component: User }
]
})
現(xiàn)在像/user/foo和/user/bar都將映射到相同的路由。
一個路徑參數(shù)使用冒號 :標記。當(dāng)匹配到一個路由時,參數(shù)值會被設(shè)置到this.$route.params,可以在每個組件內(nèi)使用。于是,我們可以更新User的模板,輸出當(dāng)前用戶的ID。
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
你可以在一個路由中設(shè)置多段路徑參數(shù),對應(yīng)的值都會設(shè)置到$route.params中。
| 模式 | 匹配路徑 | $route.params |
|---|---|---|
| /user/:username | /user/evan | { username: 'evan' } |
| /user/:username/post/:post_id | /user/evan/post/123 | { username: 'evan', post_id: 123 } |
響應(yīng)路由參數(shù)的變化
當(dāng)使用路由參數(shù)時,例如從/user/foo導(dǎo)航到/user/bar,原來的組件實例會被復(fù)用。因為兩個路由都渲染同個組件,比起銷毀再創(chuàng)建,復(fù)用則顯得更加高效。不過,這也意味著組件的生命周期鉤子不會再被調(diào)用。
復(fù)用組件時,想對路由參數(shù)的變化作出響應(yīng)的話,你可以簡單地watch(監(jiān)測變化)$route對象。
const User = {
template: '...',
watch: {
'$route' (to, from) {
// 對路由變化作出響應(yīng)...
}
}
}
或者使用beforeRouteUpdate守衛(wèi)。
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
捕獲所有路由或 404 Not found 路由
常規(guī)參數(shù)只會匹配被/分隔的URL片段中的字符。如果想匹配任意路徑,我們可以使用通配符(*):
{
// 會匹配所有路徑
path: '*'
}
{
// 會匹配以 `/user-` 開頭的任意路徑
path: '/user-*'
}
當(dāng)使用通配符路由時,請確保路由的順序是正確的,也就是說含有通配符的路由應(yīng)該放在最后。路由{ path: '*' }通常用于客戶端404錯誤。如果你使用了History模式,請確保正確配置你的服務(wù)器。
當(dāng)使用一個通配符時,$route.params內(nèi)會自動添加一個名為pathMatch參數(shù)。它包含了URL通過通配符被匹配的部分:
// 給出一個路由 { path: '/user-*' }
this.$router.push('/user-admin')
this.$route.params.pathMatch // 'admin'
// 給出一個路由 { path: '*' }
this.$router.push('/non-existing')
this.$route.params.pathMatch // '/non-existing'
高級匹配模式
vue-router使用path-to-regexp作為路徑匹配引擎,所以支持很多高級的匹配模式,例如:可選的動態(tài)路徑參數(shù)、匹配零個或多個、一個或多個,甚至是自定義正則匹配。
匹配優(yōu)先級
有時候,同一個路徑可以匹配多個路由,此時,匹配的優(yōu)先級就按照路由的定義順序:誰先定義的,誰的優(yōu)先級就最高。
嵌套路由
實際生活中的應(yīng)用界面,通常由多層嵌套的組件組合而成。同樣地,URL中各段動態(tài)路徑也按某種結(jié)構(gòu)對應(yīng)嵌套的各層組件。
/user/foo/profile /user/foo/posts
+------------------+ +-----------------+
| User | | User |
| +--------------+ | | +-------------+ |
| | Profile | | +------------> | | Posts | |
| | | | | | | |
| +--------------+ | | +-------------+ |
+------------------+ +-----------------+
<div id="app">
<router-view></router-view>
</div>
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
這里的<router-view>是最頂層的出口,渲染最高級路由匹配到的組件。同樣地,一個被渲染組件同樣可以包含自己的嵌套<router-view>。例如,在User組件的模板添加一個<router-view>。
const User = {
template: `
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>
`
}
要在嵌套的出口中渲染組件,需要在VueRouter的參數(shù)中使用children配置。
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// 當(dāng) /user/:id/profile匹配成功,
// UserProfile會被渲染在User的<router-view>中
path: 'profile',
component: UserProfile
},
{
// 當(dāng) /user/:id/posts匹配成功
// UserPosts會被渲染在User的<router-view>中
path: 'posts',
component: UserPosts
}
]
}
]
})
要注意,以/開頭的嵌套路徑會被當(dāng)作根路徑。 這讓你充分的使用嵌套組件而無須設(shè)置嵌套的路徑。
children配置就是像routes配置一樣的路由配置數(shù)組,所以可以嵌套多層路由。
此時,基于上面的配置,當(dāng)你訪問/user/foo時,User的出口是不會渲染任何東西,這是因為沒有匹配到合適的子路由。如果你想要渲染點什么,可以提供一個空的子路由。
const router = new VueRouter({
routes: [
{
path: '/user/:id', component: User,
children: [
// 當(dāng) /user/:id 匹配成功,
// UserHome 會被渲染在 User 的 <router-view> 中
{ path: '', component: UserHome },
// ...其他子路由
]
}
]
})
編程式的導(dǎo)航
除了使用<router-link>創(chuàng)建a標簽來定義導(dǎo)航鏈接,我們還可以借助router的實例方法,通過編寫代碼來實現(xiàn)。
router.push(location,onComplete?,onAbort?)
在Vue實例內(nèi)部,可以通過$router訪問路由實例。因此你可以調(diào)用 this.$router.push。
想要導(dǎo)航到不同的URL,則使用router.push方法。這個方法會向history棧添加一個新的記錄,所以,當(dāng)用戶點擊瀏覽器后退按鈕時,則回到之前的URL。
當(dāng)你點擊<router-link>時,這個方法會在內(nèi)部調(diào)用,所以說,點擊<router-link :to="...">等同于調(diào)用router.push(...)。
| 聲明式 | 編程式 |
|---|---|
<router-link :to="..."> |
router.push(...) |
該方法的參數(shù)可以是一個字符串路徑,或者一個描述地址的對象。
// 字符串
router.push('home')
// 對象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
// 帶查詢參數(shù),變成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
注意:如果提供了path,params會被忽略,上述例子中的query并不屬于這種情況。取而代之的是下面例子的做法,你需要提供路由的name或手寫完整的帶有參數(shù)的path。
const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 這里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user
同樣的規(guī)則也適用于router-link組件的to屬性。
在2.2.0+,可選的在router.push或router.replace中提供onComplete和onAbort回調(diào)作為第二個和第三個參數(shù)。這些回調(diào)將會在導(dǎo)航成功完成 (在所有的異步鉤子被解析之后) 或終止 (導(dǎo)航到相同的路由、或在當(dāng)前導(dǎo)航完成之前導(dǎo)航到另一個不同的路由) 的時候進行相應(yīng)的調(diào)用。
注意:如果目的地和當(dāng)前路由相同,只有參數(shù)發(fā)生了改變 (比如從一個用戶資料到另一個/users/1->/users/2),你需要使用beforeRouteUpdate來響應(yīng)這個變化 (比如抓取用戶信息)。
router.replace(location,onComplete?,onAbort?)
跟router.push很像,唯一的不同就是,它不會向history添加新記錄,而是跟它的方法名一樣——替換掉當(dāng)前的history記錄。
| 聲明式 | 編程式 |
|---|---|
<router-link :to="..." replace> |
router.replace(...) |
router.go(n)
這個方法的參數(shù)是一個整數(shù),意思是在 history 記錄中向前或者后退多少步,類似 window.history.go(n)。
// 在瀏覽器記錄中前進一步,等同于history.forward()
router.go(1)
// 后退一步記錄,等同于history.back()
router.go(-1)
// 前進 3 步記錄
router.go(3)
// 如果 history 記錄不夠用,那就默默地失敗唄
router.go(-100)
router.go(100)
操作History
你也許注到router.push、router.replace和router.go跟window.history.pushState、window.history.replaceState和window.history.go好像,實際上它們確實是效仿window.historyAPI的。
還有值得提及的,vue-router的導(dǎo)航方法(push、replace、go)在各類路由模式(history、hash和abstract)下表現(xiàn)一致。
命名路由
有時候,通過一個名稱來標識一個路由顯得更方便一些,特別是在鏈接一個路由,或者是執(zhí)行一些跳轉(zhuǎn)的時候??梢栽趧?chuàng)建Router實例的時候,在routes配置中給某個路由設(shè)置名稱。
const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
})
要鏈接到一個命名路由,可以給router-link的to屬性傳一個對象。
<router-link:to="{name:'user',params:{userId:123}}">User</router-link>
這跟代碼調(diào)用router.push()是一回事。
router.push({ name:'user',params:{ userId:123 }})
這兩種方式都會把路由導(dǎo)航到/user/123路徑。
命名視圖
有時候想同時(同級)展示多個視圖,而不是嵌套展示,例如創(chuàng)建一個布局,有sidebar和main兩個視圖,這個時候命名視圖就派上用場了。你可以在界面中擁有多個單獨命名的視圖,而不是只有一個單獨的出口。如果router-view沒有設(shè)置名字,那么默認為default。
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
一個視圖使用一個組件渲染,因此對于同個路由,多個視圖就需要多個組件。確保正確使用components配置(帶上s)。
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
嵌套命名視圖
我們也有可能使用命名視圖創(chuàng)建嵌套視圖的復(fù)雜布局。這時你也需要命名用到的嵌套router-view組件。我們以一個設(shè)置面板為例:
/settings/emails /settings/profile
+-----------------------------------+ +------------------------------+
| UserSettings | | UserSettings |
| +-----+-------------------------+ | | +-----+--------------------+ |
| | Nav | UserEmailsSubscriptions | | +------------> | | Nav | UserProfile | |
| | +-------------------------+ | | | +--------------------+ |
| | | | | | | | UserProfilePreview | |
| +-----+-------------------------+ | | +-----+--------------------+ |
+-----------------------------------+ +------------------------------+
-
Nav只是一個常規(guī)組件。 -
UserSettings是一個視圖組件。 -
UserEmailsSubscriptions、UserProfile、UserProfilePreview是嵌套的視圖組件。
UserSettings組件的<template>部分應(yīng)該是類似下面的這段代碼:
<!-- UserSettings.vue -->
<div>
<h1>User Settings</h1>
<NavBar/>
<router-view/>
<router-view name="helper"/>
</div>
然后你可以用這個路由配置完成該布局。
{
path: '/settings',
// 你也可以在頂級路由就配置命名視圖
component: UserSettings,
children: [{
path: 'emails',
component: UserEmailsSubscriptions
}, {
path: 'profile',
components: {
default: UserProfile,
helper: UserProfilePreview
}
}]
}
重定向和別名
重定向
重定向也是通過routes配置來完成,下面例子是從/a重定向到/b。
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' }
]
})
重定向的目標也可以是一個命名的路由。
const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
})
甚至是一個方法,動態(tài)返回重定向目標。
const router = new VueRouter({
routes: [
{ path: '/a', redirect: to => {
// 方法接收 目標路由 作為參數(shù)
// return 重定向的 字符串路徑/路徑對象
}}
]
})
注意導(dǎo)航守衛(wèi)并沒有應(yīng)用在跳轉(zhuǎn)路由上,而僅僅應(yīng)用在其目標上。在下面這個例子中,為/a路由添加一個beforeEach或beforeLeave守衛(wèi)并不會有任何效果。
別名
重定向的意思是,當(dāng)用戶訪問/a時,URL將會被替換成/b,然后匹配路由為/b,那么別名又是什么呢?/a的別名是/b,意味著,當(dāng)用戶訪問/b時,URL會保持為/b,但是路由匹配則為/a,就像用戶訪問`/a 一樣。
const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})
路由組件傳參
在組件中使用$route會使之與其對應(yīng)路由形成高度耦合,從而使組件只能在某些特定的URL上使用,限制了其靈活性。
使用props將組件和路由解耦:
取代與$route的耦合
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
通過props解耦
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// 對于包含命名視圖的路由,你必須分別為每個命名視圖添加 `props` 選項:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
這樣你便可以在任何地方使用該組件,使得該組件更易于重用和測試。
布爾模式
如果props被設(shè)置為true,route.params將會被設(shè)置為組件屬性。
對象模式
如果props是一個對象,它會被按原樣設(shè)置為組件屬性。當(dāng)props是靜態(tài)的時候有用。
const router = new VueRouter({
routes: [
{ path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
]
})
函數(shù)模式
你可以創(chuàng)建一個函數(shù)返回props。這樣你便可以將參數(shù)轉(zhuǎn)換成另一種類型,將靜態(tài)值與基于路由的值結(jié)合等等。
const router = new VueRouter({
routes: [
{ path:'/search',component:SearchUser,props:(route)=>({ query:route.query.q }) }
]
})
URL /search?q=vue會將{query: 'vue'}作為屬性傳遞給SearchUser組件。
請盡可能保持props函數(shù)為無狀態(tài)的,因為它只會在路由發(fā)生變化時起作用。如果你需要狀態(tài)來定義props,請使用包裝組件,這樣Vue才可以對狀態(tài)變化做出反應(yīng)。
HTML5 History模式
vue-router默認hash模式——使用URL的hash來模擬一個完整的URL,于是當(dāng)URL改變時,頁面不會重新加載。
如果不想要hash,我們可以用路由的history模式,這種模式充分利用history.pushState API來完成URL跳轉(zhuǎn)而無須重新加載頁面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
當(dāng)你使用history模式時,URL就像正常的url,例如http://yoursite.com/user/id。
不過這種模式還需要后臺配置支持。因為我們的應(yīng)用是個單頁客戶端應(yīng)用,如果后臺沒有正確的配置,當(dāng)用戶在瀏覽器直接訪問http://oursite.com/user/id就會返回404,這就不好看了。
所以呢,要在服務(wù)端增加一個覆蓋所有情況的候選資源:如果URL匹配不到任何靜態(tài)資源,則應(yīng)該返回同一個index.html頁面,這個頁面就是你app依賴的頁面。
這么做以后,你的服務(wù)器就不再返回404錯誤頁面,因為對于所有路徑都會返回index.html文件。為了避免這種情況,你應(yīng)該在Vue應(yīng)用里面覆蓋所有的路由情況,然后在給出一個404頁面。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})