vue 路由 vue-router
前面的話
在Web開發(fā)中,路由是指根據(jù)URL分配到對應(yīng)的處理程序。對于大多數(shù)單頁面應(yīng)用,都推薦使用官方支持的vue-router。Vue-router通過管理URL,實(shí)現(xiàn)URL和組件的對應(yīng),以及通過URL進(jìn)行組件之間的切換。本文將詳細(xì)介紹Vue路由vue-router
安裝
在使用vue-router之前,首先需要安裝該插件
npm install vue-router
如果在一個(gè)模塊化工程中使用它,必須要通過 Vue.use()
明確地安裝路由功能
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter)
如果使用全局的 script 標(biāo)簽,則無須如此
使用
用Vue.js + vue-router創(chuàng)建單頁應(yīng)用非常簡單。使用Vue.js ,已經(jīng)可以通過組合組件來組成應(yīng)用程序,把vue-router添加進(jìn)來,需要做的是,將組件(components)映射到路由(routes),然后告訴 vue-router 在哪里渲染它們
下面是一個(gè)實(shí)例
<div id="app"> <h1>Hello App!</h1> <p> <!-- 使用 router-link 組件來導(dǎo)航,通過傳入 `to` 屬性指定鏈接,<router-link> 默認(rèn)會(huì)被渲染成一個(gè) `<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> <script src="vue.js"></script> <script src="vue-router.js"></script> <script>const Foo = { template: '<div>foo</div>'= { template: '<div>bar</div>'const routes ='/foo''/bar'const router = const app = </script>
路由模式
vue-router
默認(rèn) hash 模式 —— 使用 URL 的 hash 來模擬一個(gè)完整的 URL,于是當(dāng) URL 改變時(shí),頁面不會(huì)重新加載
http://localhost:8080/#/Hello
如果不想要很丑的 hash,可以用路由的 history 模式,這種模式充分利用 history.pushState
API 來完成 URL 跳轉(zhuǎn)而無須重新加載頁面
const router = new VueRouter({ mode: 'history', routes: [...] })
當(dāng)使用 history 模式時(shí),URL 就像正常的 url
http://localhost:8080/Hello
不過這種模式需要后臺配置支持。如果后臺沒有正確的配置,當(dāng)用戶在瀏覽器直接訪問 http://oursite.com/user/id
就會(huì)返回 404
【服務(wù)器配置】
如果要使用history模式,則需要進(jìn)行服務(wù)器配置
所以,要在服務(wù)端增加一個(gè)覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態(tài)資源,則應(yīng)該返回同一個(gè) index.html
頁面,這個(gè)頁面就是app 依賴的頁面
下面是一些配置的例子
apache
以wamp為例,需要對httpd.conf配置文件進(jìn)行修改
首先,去掉rewrite_module前面的#號注釋
LoadModule rewrite_module modules/mod_rewrite.so
然后,將文檔所有的AllowOverride設(shè)置為all
AllowOverride all
最后,需要保存一個(gè).htaccess文件放置在根路徑下面,文件內(nèi)容如下
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule>
nginx
location / { try_files $uri $uri/ /index.html; }
【注意事項(xiàng)】
這么做以后,服務(wù)器就不再返回404錯(cuò)誤頁面,因?yàn)閷τ谒新窂蕉紩?huì)返回 index.html
文件。為了避免這種情況,應(yīng)該在Vue應(yīng)用里面覆蓋所有的路由情況,然后再給出一個(gè)404頁面
const router = new VueRouter({ mode: 'history', routes: [ { path: '*', component: NotFoundComponent } ] })
或者,如果是用 Node.js 作后臺,可以使用服務(wù)端的路由來匹配 URL,當(dāng)沒有匹配到路由的時(shí)候返回 404,從而實(shí)現(xiàn) fallback
const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } const NotFound = {template:'<div>not found</div>'} const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar }, { path: '*', component: NotFound}, ]
重定向和別名
【重定向】
重定向通過 routes
配置來完成,下面例子是從 /a
重定向到 /b
const router = new VueRouter({ routes: [ { path: '/a', redirect: '/b' } ] })
重定向的目標(biāo)也可以是一個(gè)命名的路由:
const router = new VueRouter({ routes: [ { path: '/a', redirect: { name: 'foo' }} ] })
甚至是一個(gè)方法,動(dòng)態(tài)返回重定向目標(biāo):
const router = '/a', redirect: to => return '/home'
對于不識別的URL地址來說,常常使用重定向功能,將頁面定向到首頁顯示
const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar }, { path: '*', redirect: "/foo"}, ]
【別名】
重定向是指,當(dāng)用戶訪問 /a
時(shí),URL 將會(huì)被替換成 /b
,然后匹配路由為 /b
,那么別名是什么呢?/a
的別名是 /b
,意味著,當(dāng)用戶訪問 /b
時(shí),URL 會(huì)保持為 /b
,但是路由匹配則為 /a
,就像用戶訪問 /a
一樣
上面對應(yīng)的路由配置為
const router = new VueRouter({ routes: [ { path: '/a', component: A, alias: '/b' } ] })
『別名』的功能可以自由地將 UI 結(jié)構(gòu)映射到任意的 URL,而不是受限于配置的嵌套路由結(jié)構(gòu)
處理首頁訪問時(shí),常常將index設(shè)置為別名,比如將'/home'的別名設(shè)置為'/index'。但是,要注意的是,<router-link to="/home">的樣式在URL為/index時(shí)并不會(huì)顯示。因?yàn)椋瑀outer-link只識別出了home,而無法識別index
根路徑
設(shè)置根路徑,需要將path設(shè)置為'/'
<p> <router-link to="/">index</router-link> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p>const routes = [ { path: '/', component: Home }, { path: '/foo', component: Foo }, { path: '/bar', component: Bar }, ]
但是,由于默認(rèn)使用的是全包含匹配,即'/foo'、'/bar'也可以匹配到'/',如果需要精確匹配,僅僅匹配'/',則需要在router-link中設(shè)置exact屬性
<p> <router-link to="/" exact>index</router-link> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p>const routes = [ { path: '/', component: Home }, { path: '/foo', component: Foo }, { path: '/bar', component: Bar }, ]
嵌套路由
實(shí)際生活中的應(yīng)用界面,通常由多層嵌套的組件組合而成。同樣地,URL中各段動(dòng)態(tài)路徑也按某種結(jié)構(gòu)對應(yīng)嵌套的各層組件
/user/foo/profile /user/foo/posts+------------------+ +-----------------+ | User | | User | | +--------------+ | | +-------------+ | | | Profile | | +------------> | | Posts | | | | | | | | | | | +--------------+ | | +-------------+ | +------------------+ +-----------------+
借助 vue-router
,使用嵌套路由配置,就可以很簡單地表達(dá)這種關(guān)系
<div id="app"> <p> <router-link to="/" exact>index</router-link> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <router-view></router-view> </div>
const Home = { template: '<div>home</div>' } const Foo = { template: ` <div> <p> <router-link to="/foo/foo1">to Foo1</router-link> <router-link to="/foo/foo2">to Foo2</router-link> <router-link to="/foo/foo3">to Foo3</router-link> </p> <router-view></router-view> </div> ` } const Bar = { template: '<div>bar</div>' } const Foo1 = { template: '<div>Foo1</div>' } const Foo2 = { template: '<div>Foo2</div>' } const Foo3 = { template: '<div>Foo3</div>' }
const routes = [ { path: '/', component: Home }, { path: '/foo', component: Foo ,children:[ {path:'foo1',component:Foo1}, {path:'foo2',component:Foo2}, {path:'foo3',component:Foo3}, ]}, { path: '/bar', component: Bar }, ]
要特別注意的是,router的構(gòu)造配置中,children屬性里的path屬性只設(shè)置為當(dāng)前路徑,因?yàn)槠鋾?huì)依據(jù)層級關(guān)系;而在router-link的to屬性則需要設(shè)置為完全路徑
如果要設(shè)置默認(rèn)子路由,即點(diǎn)擊foo時(shí),自動(dòng)觸發(fā)foo1,則需要進(jìn)行如下修改。將router配置對象中children屬性的path屬性設(shè)置為'',并將對應(yīng)的router-link的to屬性設(shè)置為'/foo'
const Foo = { template: ` <div> <p> <router-link to="/foo" exact>to Foo1</router-link> <router-link to="/foo/foo2">to Foo2</router-link> <router-link to="/foo/foo3">to Foo3</router-link> </p> <router-view></router-view> </div> ` }
const routes = [ { path: '/', component: Home }, { path: '/foo', component: Foo ,children:[ {path:'',component:Foo1}, {path:'foo2',component:Foo2}, {path:'foo3',component:Foo3}, ]}, { path: '/bar', component: Bar }, ]
命名路由
有時(shí),通過一個(gè)名稱來標(biāo)識一個(gè)路由顯得更方便,特別是在鏈接一個(gè)路由,或者是執(zhí)行一些跳轉(zhuǎn)時(shí)。可以在創(chuàng)建Router實(shí)例時(shí),在routes
配置中給某個(gè)路由設(shè)置名稱
const router = new VueRouter({ routes: [ { path: '/user/:userId', name: 'user', component: User } ] })
要鏈接到一個(gè)命名路由,可以給 router-link
的 to
屬性傳一個(gè)對象:
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
這跟代碼調(diào)用 router.push()
是一回事
router.push({ name: 'user', params: { userId: 123 }})
這兩種方式都會(huì)把路由導(dǎo)航到 /user/123
路徑
命名路由的常見用途是替換router-link中的to屬性,如果不使用命名路由,由router-link中的to屬性需要設(shè)置全路徑,不夠靈活,且修改時(shí)較麻煩。使用命名路由,只需要使用包含name屬性的對象即可
[注意]如果設(shè)置了默認(rèn)子路由,則不要在父級路由上設(shè)置name屬性
<div id="app"> <p> <router-link to="/" exact>index</router-link> <router-link :to="{ name: 'foo1' }">Go to Foo</router-link> <router-link :to="{ name: 'bar' }">Go to Bar</router-link> </p> <router-view></router-view></div>
const Home = { template: '<div>home</div>' } const Foo = { template: ` <div> <p> <router-link :to="{ name: 'foo1' }" exact>to Foo1</router-link> <router-link :to="{ name: 'foo2' }" >to Foo2</router-link> <router-link :to="{ name: 'foo3' }" >to Foo3</router-link> </p> <router-view></router-view> </div> ` } const Bar = { template: '<div>bar</div>' } const Foo1 = { template: '<div>Foo1</div>' } const Foo2 = { template: '<div>Foo2</div>' } const Foo3 = { template: '<div>Foo3</div>' }
const routes = [ { path: '/', name:'home', component: Home }, { path: '/foo', component: Foo ,children:[ {path:'',name:'foo1', component:Foo1}, {path:'foo2',name:'foo2', component:Foo2}, {path:'foo3',name:'foo3', component:Foo3}, ]}, { path: '/bar', name:'bar', component: Bar }, ]
命名視圖
有時(shí)候想同時(shí)(同級)展示多個(gè)視圖,而不是嵌套展示,例如創(chuàng)建一個(gè)布局,有 sidebar
(側(cè)導(dǎo)航) 和 main
(主內(nèi)容) 兩個(gè)視圖,這個(gè)時(shí)候命名視圖就派上用場了。可以在界面中擁有多個(gè)單獨(dú)命名的視圖,而不是只有一個(gè)單獨(dú)的出口。如果 router-view
沒有設(shè)置名字,那么默認(rèn)為 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>
一個(gè)視圖使用一個(gè)組件渲染,因此對于同個(gè)路由,多個(gè)視圖就需要多個(gè)組件。確保正確使用components
配置
const router = new VueRouter({ routes: [ { path: '/', components: { default: Foo, a: Bar, b: Baz } } ] })
下面是一個(gè)實(shí)例
<div id="app"> <p> <router-link to="/" exact>index</router-link> <router-link :to="{ name: 'foo' }">Go to Foo</router-link> <router-link :to="{ name: 'bar' }">Go to Bar</router-link> </p> <router-view></router-view> <router-view name="side"></router-view></div>
const Home = { template: '<div>home</div>' } const Foo = { template: '<div>Foo</div>'} const MainBar = { template: '<div>mainBar</div>' } const SideBar = { template: '<div>sideBar</div>' } const routes = [ { path: '/', name:'home', component: Home }, { path: '/foo', name:'foo', component: Foo}, { path: '/bar', name:'bar', components: { default: MainBar, side:SideBar } }, ]
動(dòng)態(tài)路徑
經(jīng)常需要把某種模式匹配到的所有路由,全都映射到同個(gè)組件。例如,有一個(gè) User
組件,對于所有 ID 各不相同的用戶,都要使用這個(gè)組件來渲染。那么,可以在 vue-router
的路由路徑中使用動(dòng)態(tài)路徑參數(shù)(dynamic segment)來達(dá)到這個(gè)效果
const User = { template: '<div>User</div>'} const router = new VueRouter({ routes: [ // 動(dòng)態(tài)路徑參數(shù)以冒號開頭 { path: '/user/:id', component: User } ] })
現(xiàn)在,像 /user/foo
和 /user/bar
都將映射到相同的路由
下面是一個(gè)比較完整的實(shí)例,path:'/user/:id?'表示有沒有子路徑都可以匹配
<div id="app"> <router-view></router-view> <br> <p> <router-link to="/" exact>index</router-link> <router-link :to="{name:'user'}">User</router-link> <router-link :to="{name:'bar'}">Go to Bar</router-link> </p> </div>const home = { template: '<div>home</div>'}; const bar = { template: '<div>bar</div>'}; const user = {template: `<div> <p>user</p> <router-link style="margin: 0 10px" :to="'/user/' + item.id" v-for="item in userList" key="item.id">{{item.userName}}</router-link> </div>`, data(){ return{userList:[{id:1,userName:'u1'},{id:2,userName:'u2'},{id:3,userName:'u3'}]} } }; const app = new Vue({ el:'#app', router:new VueRouter({ routes: [ { path: '/', name:'home', component:home }, { path: '/user/:id?', name:'user', component:user}, { path: '/bar', name:'bar', component:bar}, ], }), })
一個(gè)路徑參數(shù)使用冒號 :
標(biāo)記。當(dāng)匹配到一個(gè)路由時(shí),參數(shù)值會(huì)被設(shè)置到 this.$route.params
,可以在每個(gè)組件內(nèi)使用。于是,可以更新 User
的模板,輸出當(dāng)前用戶的 ID:
const User = { template: '<div>User {{ $route.params.id }}</div>'}
下面是一個(gè)實(shí)例
<div id="app"> <p> <router-link to="/user/foo">/user/foo</router-link> <router-link to="/user/bar">/user/bar</router-link> </p> <router-view></router-view> </div> <script src="vue.js"></script> <script src="vue-router.js"></script> <script>const User = { template: `<div>User {{ $route.params.id }}</div>`} const router = new VueRouter({ routes: [ { path: '/user/:id', component: User } ] }) const app = new Vue({ router }).$mount('#app')</script>
可以在一個(gè)路由中設(shè)置多段『路徑參數(shù)』,對應(yīng)的值都會(huì)設(shè)置到 $route.params
中。例如:
/user/:username /user/evan { username: 'evan' } /user/:username/post/:post_id /user/evan/post/123 { username: 'evan', post_id: 123 }
除了 $route.params
外,$route
對象還提供了其它有用的信息,例如,$route.query
(如果 URL 中有查詢參數(shù))、$route.hash
等等
【響應(yīng)路由參數(shù)的變化】
使用路由參數(shù)時(shí),例如從 /user/foo
導(dǎo)航到 user/bar
,原來的組件實(shí)例會(huì)被復(fù)用。因?yàn)閮蓚€(gè)路由都渲染同個(gè)組件,比起銷毀再創(chuàng)建,復(fù)用則顯得更加高效。不過,這也意味著組件的生命周期鉤子不會(huì)再被調(diào)用
復(fù)用組件時(shí),想對路由參數(shù)的變化作出響應(yīng)的話,可以簡單地 watch(監(jiān)測變化) $route
對象:
const User = { template: '...', watch: { '$route' (to, from) { // 對路由變化作出響應(yīng)... } } }
[注意]有時(shí)同一個(gè)路徑可以匹配多個(gè)路由,此時(shí),匹配的優(yōu)先級就按照路由的定義順序:誰先定義的,誰的優(yōu)先級就最高
下面是一個(gè)實(shí)例
const home = { template: '<div>home</div>'}; const bar = { template: '<div>bar</div>'}; const user = {template: `<div> <p>user</p> <router-link style="margin: 0 10px" :to="'/user/' +item.type + '/'+ item.id" v-for="item in userList" key="item.id">{{item.userName}}</router-link> <div v-if="$route.params.id"> <div>id:{{userInfo.id}};userName:{{userInfo.userName}} ;type:{{userInfo.type}};</div> </div> </div>`, data(){ return{ userList:[{id:1,type:'vip',userName:'u1'},{id:2,type:'common',userName:'u2'},{id:3,type:'vip',userName:'u3'}], userInfo:null, } }, methods:{ getData(){ let id = this.$route.params.id; if(id){ this.userInfo = this.userList.filter((item)=>{ return item.id == id; })[0] }else{ this.userInfo = {}; } } }, created(){ this.getData(); }, watch:{ $route(){ this.getData(); }, } }; const app = new Vue({ el:'#app', router:new VueRouter({ routes: [ { path: '/', name:'home', component:home }, { path: '/user/:type?/:id?', name:'user', component:user}, { path: '/bar', name:'bar', component:bar}, ], }), })
查詢字符串
實(shí)現(xiàn)子路由,除了使用動(dòng)態(tài)參數(shù),也可以使用查詢字符串
const home = { template: '<div>home</div>'}; const bar = { template: '<div>bar</div>'}; const user = {template: `<div> <p>user</p> <router-link style="margin: 0 10px" :to="'/user/' +item.type + '/'+ item.id" v-for="item in userList" key="item.id">{{item.userName}}</router-link> <div v-if="$route.params.id"> <div>id:{{userInfo.id}};userName:{{userInfo.userName}} ;type:{{userInfo.type}};</div> <router-link to="?info=follow" exact>關(guān)注</router-link> <router-link to="?info=share" exact>分享</router-link> </div> </div>`, data(){ return{ userList:[{id:1,type:'vip',userName:'u1'},{id:2,type:'common',userName:'u2'},{id:3,type:'vip',userName:'u3'}], userInfo:null, } }, methods:{ getData(){ let id = this.$route.params.id; if(id){ this.userInfo = this.userList.filter((item)=>{ return item.id == id; })[0] }else{ this.userInfo = {}; } } }, created(){ this.getData(); }, watch:{ $route(){ this.getData(); }, } }; const app = new Vue({ el:'#app', router:new VueRouter({ routes: [ { path: '/', name:'home', component:home }, { path: '/user/:type?/:id?', name:'user', component:user}, { path: '/bar', name:'bar', component:bar}, ], }), })
當(dāng)需要設(shè)置默認(rèn)查詢字符串時(shí),進(jìn)行如下設(shè)置
const user = { template: `<div> <p>user</p> <router-link style="margin: 0 10px" :to="{path:'/user/' +item.type + '/'+ item.id,query:{info:'follow'}}" v-for="item in userList" key="item.id">{{item.userName}}</router-link> <div v-if="$route.params.id"> <div>id:{{userInfo.id}};userName:{{userInfo.userName}} ;type:{{userInfo.type}};</div> <router-link to="?info=follow" exact>關(guān)注</router-link> <router-link to="?info=share" exact>分享</router-link> {{$route.query}} </div> </div>`, data() { return { userList: [{ id: 1, type: 'vip', userName: 'u1' }, { id: 2, type: 'common', userName: 'u2' }, { id: 3, type: 'vip', userName: 'u3' }], userInfo: null, } }, methods: { getData() { let id = this.$route.params.id; if (id) { this.userInfo = this.userList.filter((item) => { return item.id == id; })[0] } else { this.userInfo = {}; } } }, created() { this.getData(); }, watch: { $route() { this.getData(); }, } };
滾動(dòng)行為
使用前端路由,當(dāng)切換到新路由時(shí),想要頁面滾到頂部,或者是保持原先的滾動(dòng)位置,就像重新加載頁面那樣。 vue-router
能做到,而且更好,它可以自定義路由切換時(shí)頁面如何滾動(dòng)
[注意]這個(gè)功能只在 HTML5 history 模式下可用
當(dāng)創(chuàng)建一個(gè) Router 實(shí)例,可以提供一個(gè) scrollBehavior
方法。該方法在前進(jìn)、后退或切換導(dǎo)航時(shí)觸發(fā)
const router = new VueRouter({ routes: [...], scrollBehavior (to, from, savedPosition) { // return 期望滾動(dòng)到哪個(gè)的位置 } })
scrollBehavior
方法返回 to
和 from
路由對象。第三個(gè)參數(shù) savedPosition
當(dāng)且僅當(dāng) popstate
導(dǎo)航 (通過瀏覽器的 前進(jìn)/后退 按鈕觸發(fā)) 時(shí)才可用,返回滾動(dòng)條的坐標(biāo){x:number,y:number}
如果返回一個(gè)布爾假的值,或者是一個(gè)空對象,那么不會(huì)發(fā)生滾動(dòng)
scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } }
對于所有路由導(dǎo)航,簡單地讓頁面滾動(dòng)到頂部。返回 savedPosition
,在按下 后退/前進(jìn) 按鈕時(shí),就會(huì)像瀏覽器的原生表現(xiàn)那樣:
scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition } else { return { x: 0, y: 0 } } }
下面是一個(gè)實(shí)例,點(diǎn)擊導(dǎo)航進(jìn)行切換時(shí),滾動(dòng)到頁面頂部;通過前進(jìn)、后退按鈕進(jìn)行切換時(shí),保持坐標(biāo)位置
const router = new VueRouter({ mode:'history', routes , scrollBehavior (to, from, savedPosition){ if(savedPosition){ return savedPosition; }else{ return {x:0,y:0} } } })
還可以模擬『滾動(dòng)到錨點(diǎn)』的行為:
scrollBehavior (to, from, savedPosition) { if (to.hash) { return { selector: to.hash } } }
下面是一個(gè)實(shí)例
<div id="app"> <router-view></router-view> <br> <p> <router-link to="/" exact>index</router-link> <router-link :to="{name:'foo' ,hash:'#abc'}">Go to Foo</router-link> <router-link :to="{ name: 'bar' }">Go to Bar</router-link> </p> </div>
const router = new VueRouter({ mode:'history', routes , scrollBehavior (to, from, savedPosition){ if(to.hash){ return { selector: to.hash } } if(savedPosition){ return savedPosition; }else{ return {x:0,y:0} } } })
過渡動(dòng)效
<router-view>
是基本的動(dòng)態(tài)組件,所以可以用 <transition>
組件給它添加一些過渡效果:
<transition> <router-view></router-view> </transition>
下面是一個(gè)實(shí)例
.router-link-active{background:pink;} .v-enter,.v-leave-to{ opacity:0; } .v-enter-active,.v-leave-active{ transition:opacity .5s; }
<div id="app"> <p> <router-link to="/" exact>index</router-link> <router-link :to="{name:'foo'}">Go to Foo</router-link> <router-link :to="{ name: 'bar' }">Go to Bar</router-link> <transition> <router-view></router-view> </transition> </p></div>
【單個(gè)路由過渡】
上面的用法會(huì)給所有路由設(shè)置一樣的過渡效果,如果想讓每個(gè)路由組件有各自的過渡效果,可以在各路由組件內(nèi)使用 <transition>
并設(shè)置不同的 name
const Foo = { template: ` <transition name="slide"> <div class="foo">...</div> </transition> ` } const Bar = { template: ` <transition name="fade"> <div class="bar">...</div> </transition> ` }
路由元信息
定義路由的時(shí)候可以配置 meta
字段:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, children: [ { path: 'bar', component: Bar, meta: { requiresAuth: true } } ] } ] })
routes
配置中的每個(gè)路由對象被稱為路由記錄。路由記錄可以是嵌套的,因此,當(dāng)一個(gè)路由匹配成功后,它可能匹配多個(gè)路由記錄。例如,根據(jù)上面的路由配置,/foo/bar
這個(gè)URL將會(huì)匹配父路由記錄以及子路由記錄
一個(gè)路由匹配到的所有路由記錄會(huì)暴露為 $route
對象(還有在導(dǎo)航鉤子中的 route 對象)的 $route.matched
數(shù)組。因此,需要遍歷 $route.matched
來檢查路由記錄中的 meta
字段
下面例子展示在全局導(dǎo)航鉤子中檢查 meta 字段:
router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { if (!auth.loggedIn()) { next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() } } else { next() } })
【基于路由的動(dòng)態(tài)過渡】
可以基于當(dāng)前路由與目標(biāo)路由的變化關(guān)系,動(dòng)態(tài)設(shè)置過渡效果。通過使用路由元信息,在每個(gè)路由對象上設(shè)置一個(gè)index屬性保存其索引值
<style> .router-link-active{background:pink;} .left-enter{ transform:translateX(100%); } .left-leave-to{ transform:translateX(-100%); } .left-enter-active,.left-leave-active{ transition:transform .5s; } .right-enter{ transform:translateX(-100%); } .right-leave-to{ transform:translateX(100%); } .right-enter-active,.right-leave-active{ transition:transform .5s; } </style>
<div id="app"> <p> <router-link to="/" exact>index</router-link> <router-link :to="{name:'foo'}">Go to Foo</router-link> <router-link :to="{ name: 'bar' }">Go to Bar</router-link> <transition :name="transitionName"> <router-view></router-view> </transition> </p></div>
const app = new Vue({ el:'#app', router, data () { return { 'transitionName': 'left' } }, watch: { '$route' (to, from) { this['transitionName'] = to.meta.index > from.meta.index ? 'right' : 'left'; } }, })
編程式導(dǎo)航
除了使用<router-link>
創(chuàng)建a標(biāo)簽來定義導(dǎo)航鏈接,還可以借助router的實(shí)例方法,通過編寫代碼來實(shí)現(xiàn)
【router.push(location)】
想要導(dǎo)航到不同的 URL,則使用 router.push
方法。這個(gè)方法會(huì)向 history 棧添加一個(gè)新的記錄,所以,當(dāng)用戶點(diǎn)擊瀏覽器后退按鈕時(shí),則回到之前的 URL。
當(dāng)點(diǎn)擊 <router-link>
時(shí),這個(gè)方法會(huì)在內(nèi)部調(diào)用,所以說,點(diǎn)擊 <router-link :to="...">
等同于調(diào)用 router.push(...)
聲明式 編程式<router-link :to="..."> router.push(...)
在@click中,用$router表示路由對象,在methods方法中,用this.$router表示路由對象
該方法的參數(shù)可以是一個(gè)字符串路徑,或者一個(gè)描述地址的對象。例如:
// 字符串router.push('home')// 對象router.push({ path: 'home' })// 命名的路由router.push({ name: 'user', params: { userId: 123 }})// 帶查詢參數(shù),變成 /register?plan=privaterouter.push({ path: 'register', query: { plan: 'private' }})
【router.replace(location)
】
跟 router.push
很像,唯一的不同就是,它不會(huì)向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當(dāng)前的 history 記錄
聲明式 編程式<router-link :to="..." replace> router.replace(...)
【router.go(n)
】
這個(gè)方法的參數(shù)是一個(gè)整數(shù),意思是在 history 記錄中向前或者后退多少步,類似 window.history.go(n)
// 在瀏覽器記錄中前進(jìn)一步,等同于 history.forward()router.go(1)// 后退一步記錄,等同于 history.back()router.go(-1)// 前進(jìn) 3 步記錄router.go(3)// 如果 history 記錄不夠用,就靜默失敗router.go(-100) router.go(100)
【操作history】
router.push
、router.replace
和router.go
跟history.pushState、
history.replaceState
和history.go類似
, 實(shí)際上它們確實(shí)是效仿window.history
API的。vue-router的導(dǎo)航方法(push
、replace
、go
)在各類路由模式(history
、 hash
和abstract
)下表現(xiàn)一致
導(dǎo)航鉤子
vue-router
提供的導(dǎo)航鉤子主要用來攔截導(dǎo)航,讓它完成跳轉(zhuǎn)或取消。有多種方式可以在路由導(dǎo)航發(fā)生時(shí)執(zhí)行鉤子:全局的、單個(gè)路由獨(dú)享的或者組件級的
【全局鉤子】
可以使用 router.beforeEach
注冊一個(gè)全局的 before
鉤子
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ...})
當(dāng)一個(gè)導(dǎo)航觸發(fā)時(shí),全局的 before
鉤子按照創(chuàng)建順序調(diào)用。鉤子是異步解析執(zhí)行,此時(shí)導(dǎo)航在所有鉤子 resolve 完之前一直處于 等待中。
每個(gè)鉤子方法接收三個(gè)參數(shù):
to: Route: 即將要進(jìn)入的目標(biāo)路由對象 from: Route: 當(dāng)前導(dǎo)航正要離開的路由 next: Function: 一定要調(diào)用該方法來 resolve 這個(gè)鉤子。執(zhí)行效果依賴 next 方法的調(diào)用參數(shù)。
下面是next()函數(shù)傳遞不同參數(shù)的情況
next(): 進(jìn)行管道中的下一個(gè)鉤子。如果全部鉤子執(zhí)行完了,則導(dǎo)航的狀態(tài)就是 confirmed (確認(rèn)的)。 next(false): 中斷當(dāng)前的導(dǎo)航。如果瀏覽器的 URL 改變了(可能是用戶手動(dòng)或者瀏覽器后退按鈕),那么 URL 地址會(huì)重置到 from 路由對應(yīng)的地址。 next('/') 或者 next({ path: '/' }): 跳轉(zhuǎn)到一個(gè)不同的地址。當(dāng)前的導(dǎo)航被中斷,然后進(jìn)行一個(gè)新的導(dǎo)航。
[注意]確保要調(diào)用 next
方法,否則鉤子就不會(huì)被 resolved。
同樣可以注冊一個(gè)全局的 after
鉤子,不過它不像 before
鉤子那樣,after
鉤子沒有 next
方法,不能改變導(dǎo)航:
router.afterEach(route => { // ...})
下面是一個(gè)實(shí)例
const Home = { template: '<div>home</div>' } const Foo = { template: '<div>Foo</div>'} const Bar = { template: '<div>bar</div>' } const Login = { template: '<div>請登錄</div>' } const routes = [ { path: '/', name:'home', component: Home,meta:{index:0}}, { path: '/foo', name:'foo', component:Foo,meta:{index:1,login:true}}, { path: '/bar', name:'bar', component:Bar,meta:{index:2}}, { path: '/login', name:'login', component:Login,}, ] const router = new VueRouter({ routes , }) router.beforeEach((to, from, next) => { if(to.meta.login){ next('/login'); } next(); }); router.afterEach((to, from)=>{ document.title = to.name; }) const app = new Vue({ el:'#app', router, })
【單個(gè)路由獨(dú)享】
可以在路由配置上直接定義 beforeEnter
鉤子
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })
這些鉤子與全局 before
鉤子的方法參數(shù)是一樣的
【組件內(nèi)鉤子】
可以在路由組件內(nèi)直接定義以下路由導(dǎo)航鉤子
beforeRouteEnter beforeRouteUpdate (2.2 新增) beforeRouteLeave
const Foo = { template: `...`, beforeRouteEnter (to, from, next) { // 在渲染該組件的對應(yīng)路由被 confirm 前調(diào)用,不能獲取組件實(shí)例 `this`,因?yàn)楫?dāng)鉤子執(zhí)行前,組件實(shí)例還沒被創(chuàng)建 }, beforeRouteUpdate (to, from, next) { // 在當(dāng)前路由改變,但是該組件被復(fù)用時(shí)調(diào)用。舉例來說,對于一個(gè)帶有動(dòng)態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)時(shí),由于會(huì)渲染同樣的 Foo 組件,因此組件實(shí)例會(huì)被復(fù)用。而這個(gè)鉤子就會(huì)在這個(gè)情況下被調(diào)用。可以訪問組件實(shí)例 `this` }, beforeRouteLeave (to, from, next) { // 導(dǎo)航離開該組件的對應(yīng)路由時(shí)調(diào)用,可以訪問組件實(shí)例 `this` } }
beforeRouteEnter
鉤子不能訪問this
,因?yàn)殂^子在導(dǎo)航確認(rèn)前被調(diào)用,因此即將登場的新組件還沒被創(chuàng)建
不過,可以通過傳一個(gè)回調(diào)給 next
來訪問組件實(shí)例。在導(dǎo)航被確認(rèn)的時(shí)候執(zhí)行回調(diào),并且把組件實(shí)例作為回調(diào)方法的參數(shù)
beforeRouteEnter (to, from, next) { next(vm => { // 通過 `vm` 訪問組件實(shí)例 }) }
可以在 beforeRouteLeave
中直接訪問 this
。這個(gè) leave
鉤子通常用來禁止用戶在還未保存修改前突然離開。可以通過 next(false)
來取消導(dǎo)航
數(shù)據(jù)獲取
有時(shí)候,進(jìn)入某個(gè)路由后,需要從服務(wù)器獲取數(shù)據(jù)。例如,在渲染用戶信息時(shí),需要從服務(wù)器獲取用戶的數(shù)據(jù)。可以通過兩種方式來實(shí)現(xiàn):
1、導(dǎo)航完成之后獲取:先完成導(dǎo)航,然后在接下來的組件生命周期鉤子中獲取數(shù)據(jù)。在數(shù)據(jù)獲取期間顯示『加載中』之類的指示
2、導(dǎo)航完成之前獲取:導(dǎo)航完成前,在路由的 enter
鉤子中獲取數(shù)據(jù),在數(shù)據(jù)獲取成功后執(zhí)行導(dǎo)航。
從技術(shù)角度講,兩種方式都不錯(cuò) —— 就看想要的用戶體驗(yàn)是哪種
【導(dǎo)航完成后獲取】
當(dāng)使用這種方式時(shí),會(huì)馬上導(dǎo)航和渲染組件,然后在組件的 created
鉤子中獲取數(shù)據(jù)。有機(jī)會(huì)在數(shù)據(jù)獲取期間展示一個(gè) loading 狀態(tài),還可以在不同視圖間展示不同的 loading 狀態(tài)。
假設(shè)有一個(gè) Post
組件,需要基于 $route.params.id
獲取文章數(shù)據(jù):
<template> <div class="post"> <div class="loading" v-if="loading"> Loading... </div> <div v-if="error" class="error"> {{ error }} </div> <div v-if="post" class="content"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> </div></template>export default { data () { return { loading: false, post: null, error: null } }, created () { // 組件創(chuàng)建完后獲取數(shù)據(jù), // 此時(shí) data 已經(jīng)被 observed 了 this.fetchData() }, watch: { // 如果路由有變化,會(huì)再次執(zhí)行該方法 '$route': 'fetchData' }, methods: { fetchData () { this.error = this.post = null this.loading = true // replace getPost with your data fetching util / API wrapper getPost(this.$route.params.id, (err, post) => { this.loading = false if (err) { this.error = err.toString() } else { this.post = post } }) } } }
【導(dǎo)航完成前獲取數(shù)據(jù)】
通過這種方式,在導(dǎo)航轉(zhuǎn)入新的路由前獲取數(shù)據(jù)。可以在接下來的組件的 beforeRouteEnter
鉤子中獲取數(shù)據(jù),當(dāng)數(shù)據(jù)獲取成功后只調(diào)用 next
方法
export default { data () { return { post: null, error: null } }, beforeRouteEnter (to, from, next) { getPost(to.params.id, (err, post) => { if (err) { // display some global error message next(false) } else { next(vm => { vm.post = post }) } }) }, // 路由改變前,組件就已經(jīng)渲染完了 // 邏輯稍稍不同 watch: { $route () { this.post = null getPost(this.$route.params.id, (err, post) => { if (err) { this.error = err.toString() } else { this.post = post } }) } } }
在為后面的視圖獲取數(shù)據(jù)時(shí),用戶會(huì)停留在當(dāng)前的界面,因此建議在數(shù)據(jù)獲取期間,顯示一些進(jìn)度條或者別的指示。如果數(shù)據(jù)獲取失敗,同樣有必要展示一些全局的錯(cuò)誤提醒
懶加載
當(dāng)打包構(gòu)建應(yīng)用時(shí),JS包會(huì)變得非常大,影響頁面加載。如果能把不同路由對應(yīng)的組件分割成不同的代碼塊,然后當(dāng)路由被訪問的時(shí)候才加載對應(yīng)組件,這樣就更加高效了
結(jié)合 Vue 的 異步組件 和 Webpack 的代碼分割功能,輕松實(shí)現(xiàn)路由組件的懶加載。
首先,可以將異步組件定義為返回一個(gè) Promise 的工廠函數(shù)(該函數(shù)返回的Promise應(yīng)該 resolve 組件本身)
const Foo = () => Promise.resolve({ /* 組件定義對象 */ })
在 webpack 2中,使用動(dòng)態(tài) import語法來定義代碼分塊點(diǎn)(split point):
import('./Foo.vue') // returns a Promise
[注意]如果使用的是 babel,需要添加syntax-dynamic-import插件,才能使 babel 可以正確地解析語法
結(jié)合這兩者,這就是如何定義一個(gè)能夠被 webpack自動(dòng)代碼分割的異步組件
const Foo = () => import('./Foo.vue')
在路由配置中什么都不需要改變,只需要像往常一樣使用 Foo
:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo } ] })
【把組件按組分塊】
有時(shí)候想把某個(gè)路由下的所有組件都打包在同個(gè)異步塊(chunk)中。只需要使用 命名 chunk,一個(gè)特殊的注釋語法來提供chunk name(需要webpack > 2.4)
const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue') const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue') const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')
webpack 會(huì)將任何一個(gè)異步模塊與相同的塊名稱組合到相同的異步塊中