Vue Router 在實(shí)際項(xiàng)目中用到的 10 條高級(jí)技巧
前言
Vue Router 是 Vue.js 官方的路由管理器。
它和 Vue.js 的核心深度集成,讓構(gòu)建單頁面應(yīng)用變得易如反掌。
包含的功能有:
- 嵌套的路由/視圖表
- 模塊化的、基于組件的路由配置
- 路由參數(shù)、查詢、通配符
- 基于 Vue.js 過渡系統(tǒng)的視圖過渡效果
- 細(xì)粒度的導(dǎo)航控制
- 帶有自動(dòng)激活的 CSS class 的鏈接
- HTML5 歷史模式或 hash 模式,在 IE9 中自動(dòng)降級(jí)
- 自定義的滾動(dòng)條行為
本文是作者是實(shí)際項(xiàng)目中遇到的一些總結(jié),主要包括:
- 響應(yīng)路由參數(shù)變化
- 路由匹配
- 高級(jí)匹配模式
- 匹配優(yōu)先級(jí)
- push和replace的第二個(gè)第三個(gè)參數(shù)
- 路由視圖
- 重定向
- 使用props解耦$route
- 導(dǎo)航守衛(wèi)
- 守衛(wèi)的next方法
希望本文對(duì)你有所幫助。
正文
1. 響應(yīng)路由參數(shù)變化
針對(duì)復(fù)用組件(只是路由參數(shù)發(fā)生改變),生命周期函數(shù)鉤子不會(huì)被調(diào)用,如何能刷新組件了?
watch監(jiān)聽
- watch: {
- '$route' (to, from) {
- // 對(duì)路由變化作出響應(yīng)...
- }
- }
beforeRouteUpdate
- beforeRouteUpdate (to, from, next) {
- // react to route changes...
- / / don't forget to call next()
- }
2. 路由匹配
- {
- // 會(huì)匹配所有路徑
- path: '*'
- }
- {
- // 會(huì)匹配以 `/user-` 開頭的任意路徑
- path: '/user-*'
- }
注意:當(dāng)使用通配符路由時(shí),請(qǐng)確保路由的順序是正確的,也就是說含有通配符的路由應(yīng)該放在最后。路由 { path: '*' } 通常用于客戶端 404 錯(cuò)誤。
如果你使用了History 模式,請(qǐng)確保正確配置你的服務(wù)器。
當(dāng)使用一個(gè)通配符時(shí),$route.params 內(nèi)會(huì)自動(dòng)添加一個(gè)名為 pathMatch 參數(shù)。
它包含了 URL 通過通配符被匹配的部分:
- // 給出一個(gè)路由 { path: '/user-*' }
- this.$router.push('/user-admin')
- this.$route.params.pathMatch // 'admin'
- // 給出一個(gè)路由 { path: '*' }
- this.$router.push('/non-existing')
- this.$route.params.pathMatch // '/non-existing'
3. 高級(jí)匹配模式
- // 命名參數(shù)必須有"單個(gè)字符"[A-Za-z09]組成
- // ?可選參數(shù)
- { path: '/optional-params/:foo?' }
- // 路由跳轉(zhuǎn)是可以設(shè)置或者不設(shè)置foo參數(shù),可選
- <router-link to="/optional-params">/optional-params</router-link>
- <router-link to="/optional-params/foo">/optional-params/foo</router-link>
- // 零個(gè)或多個(gè)參數(shù)
- { path: '/optional-params/*' }
- <router-link to="/number">沒有參數(shù)</router-link>
- <router-link to="/number/foo000">一個(gè)參數(shù)</router-link>
- <router-link to="/number/foo111/fff222">多個(gè)參數(shù)</router-link>
- // 一個(gè)或多個(gè)參數(shù)
- { path: '/optional-params/:foo+' }
- <router-link to="/number/foo">一個(gè)參數(shù)</router-link>
- <router-link to="/number/foo/foo111/fff222">多個(gè)參數(shù)</router-link>
- // 自定義匹配參數(shù)
- // 可以為所有參數(shù)提供一個(gè)自定義的regexp,它將覆蓋默認(rèn)值([^\/]+)
- { path: '/optional-params/:id(\\d+)' }
- { path: '/optional-params/(foo/)?bar' }
4. 匹配優(yōu)先級(jí)
有時(shí)候一個(gè)路徑可能匹配多個(gè)路由。
此時(shí),匹配的優(yōu)先級(jí)就是按照路由的定義順序:先定義,優(yōu)先級(jí)最高。
5. push和replace的第二個(gè)第三個(gè)參數(shù)
在 2.2.0+版本,可選的在 router.push 或 router.replace 中提供 onComplete 和 onAbort 回調(diào)作為第二個(gè)和第三個(gè)參數(shù)。
這些回調(diào)將會(huì)在導(dǎo)航成功完成 (在所有的異步鉤子被解析之后) 或終止 (導(dǎo)航到相同的路由、或在當(dāng)前導(dǎo)航完成之前導(dǎo)航到另一個(gè)不同的路由) 的時(shí)候進(jìn)行相應(yīng)的調(diào)用。在 3.1.0+,可以省略第二個(gè)和第三個(gè)參數(shù),此時(shí)如果支持 Promise,router.push 或 router.replace 將返回一個(gè) Promise。
接下來看幾個(gè)例子來看看第二個(gè)第三個(gè)參數(shù)的調(diào)用時(shí)機(jī):
1. 組件1跳轉(zhuǎn)組件2
- // 組件1
- this.$router.push({ name: 'number' }, () => {
- console.log('組件1:onComplete回調(diào)');
- }, () => {
- console.log('組件1:onAbort回調(diào)');
- });
- // 組件2
- beforeRouteEnter(to, from, next) {
- console.log('組件2:beforeRouteEnter');
- next();
- },
- beforeCreate() {
- console.log('組件2:beforeCreate');
- },
- created() {
- console.log('組件2:created');
- }
組件之間跳轉(zhuǎn)觸發(fā)onComplete回調(diào)。
2. 組件2跳轉(zhuǎn)組件2(不帶參數(shù))
- this.$router.push({ name: 'number'}, () => {
- console.log('組件2:onComplete回調(diào)');
- }, () => {
- console.log('組件2,自我跳轉(zhuǎn):onAbort回調(diào)');
- });
組件自我跳轉(zhuǎn)當(dāng)不帶參數(shù)時(shí)觸發(fā)onAbort回調(diào)。但是當(dāng)自我跳轉(zhuǎn)帶參數(shù)時(shí)可能情況就有點(diǎn)不一樣。
3. 組件2跳轉(zhuǎn)組件2(帶參數(shù))
- this.$router.push({ name: 'number', params: { foo: this.number}}, () => {
- console.log('組件2:onComplete回調(diào)');
- }, () => {
- console.log('組件2,自我跳轉(zhuǎn):onAbort回調(diào)');
- });
組件自我?guī)?shù)跳轉(zhuǎn),onComplete回調(diào)、onAbort回調(diào)回調(diào)都不會(huì)觸發(fā)。
6. 路由視圖
有時(shí)候想同時(shí) (同級(jí)) 展示多個(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è)組件渲染,因此對(duì)于同個(gè)路由,多個(gè)視圖就需要多個(gè)組件。
確保正確使用 components 配置 (帶上 s):
- const router = new VueRouter({
- routes: [
- {
- path: '/',
- components: {
- default: Foo,
- a: Bar,
- b: Baz
- }
- }
- ]
- });
7. 重定向
- { path: '/a', redirect: '/b' }
- { path: '/a', redirect: { name: 'foo' }}
- { path: '/a', redirect: to => {
- // 方法接收 目標(biāo)路由 作為參數(shù)
- // return 重定向的 字符串路徑/路徑對(duì)象
- }}
注意:導(dǎo)航守衛(wèi)并沒有應(yīng)用在跳轉(zhuǎn)路由上,而僅僅應(yīng)用在其目標(biāo)上。
在上面這個(gè)例子中,為 /a 路由添加一個(gè) beforeEach 或 beforeLeave 守衛(wèi)并不會(huì)有任何效果。
8. 使用props解耦$route
在組件中使用 $route 會(huì)使之與其對(duì)應(yīng)路由形成高度耦合,從而使組件只能在某些特定的 URL 上使用,限制了其靈活性。
- // router文件
- // 對(duì)于包含命名視圖的路由,你必須分別為每個(gè)命名視圖添加 `props` 選項(xiàng):
- {
- path: '/number/:name',
- props: true,
- // 對(duì)象模式 props: { newsletterPopup: false }
- // 函數(shù)模式 props: (route) => ({ query: route.parmas.name })
- name: 'number',
- component: () => import( /* webpackChunkName: "number" */ './views/Number.vue')
- }
- // 組件獲取
- export default{
- props: ['name']
- }
9. 導(dǎo)航守衛(wèi)
1. 三種全局守衛(wèi)
- router.beforeEach 全局前置守衛(wèi) 進(jìn)入路由之前。
- router.beforeResolve 全局解析守衛(wèi)2.5.0新增。在beforeRouteEnter調(diào)用之后調(diào)用。
- router.afterEach 全局后置鉤子 進(jìn)入路由之后。
- // 入口文件
- import router from './router'
- // 全局前置守衛(wèi)
- router.beforeEach((to, from, next) => {
- console.log('beforeEach 全局前置守衛(wèi)');
- next();
- });
- // 全局解析守衛(wèi)
- router.beforeResolve((to, from, next) => {
- console.log('beforeResolve 全局解析守衛(wèi)');
- next();
- });
- // 全局后置守衛(wèi)
- router.afterEach((to, from) => {
- console.log('afterEach 全局后置守衛(wèi)');
- });
2. 路由獨(dú)享守衛(wèi)
beforeEnter全局前置守衛(wèi)進(jìn)入路由之前。
- {
- path: '/number/:name',
- props: true,
- name: 'number',
- // 路由獨(dú)享守衛(wèi)
- beforeEnter: (to, from, next) => {
- console.log('beforeEnter 路由獨(dú)享守衛(wèi)');
- next();
- },
- component: () => import( /* webpackChunkName: "number" */ './views/Number.vue')
- }
3. 組件內(nèi)守衛(wèi)
- beforeRouteEnter
- beforeRouteUpdate(2.2新增)
- beforeRouteLeave
- beforeRouteEnter(to, from, next) {
- // 在渲染該組件的對(duì)應(yīng)路由被 confirm 前調(diào)用
- // 不!能!獲取組件實(shí)例 `this`
- // 因?yàn)楫?dāng)守衛(wèi)執(zhí)行前,組件實(shí)例還沒被創(chuàng)建
- console.log('beforeRouteEnter 組件內(nèi)進(jìn)入守衛(wèi)');
- next();
- },
- beforeRouteUpdate(to, from, next) {
- // 在當(dāng)前路由改變,但是該組件被復(fù)用時(shí)調(diào)用
- // 舉例來說,對(duì)于一個(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`
- console.log('beforeRouteUpdate 組件內(nèi)更新守衛(wèi)');
- next();
- },
- beforeRouteLeave(to, from, next) {
- // 導(dǎo)航離開該組件的對(duì)應(yīng)路由時(shí)調(diào)用
- // 可以訪問組件實(shí)例 `this`
- console.log('beforeRouteLeave 組件內(nèi)離開守衛(wèi)');
- next();
- }
- 組件1跳轉(zhuǎn)到組件2,然后組件2跳轉(zhuǎn)組件2本身
- 組件1跳轉(zhuǎn)到組件2,然后組件2跳轉(zhuǎn)組件1
10. 守衛(wèi)的 next 方法
- next: 調(diào)用該方法 resolve 鉤子。
- next(): 進(jìn)行管道中的下一個(gè)鉤子。如果全部鉤子執(zhí)行完了,則導(dǎo)航的狀態(tài)就是 confirmed (確認(rèn)的)。
- next(false): 中斷當(dāng)前的導(dǎo)航。如果瀏覽器的 URL 改變了 (可能是用戶手動(dòng)或者瀏覽器后退按鈕),那么 URL 地址會(huì)重置到 from 路由對(duì)應(yīng)的地址。
- next('/') 或者 next({ path: '/' }): 跳轉(zhuǎn)到一個(gè)不同的地址。當(dāng)前的導(dǎo)航被中斷,然后進(jìn)行一個(gè)新的導(dǎo)航。你可以向 next 傳遞任意位置對(duì)象,且允許設(shè)置諸如 replace: true、name: 'home' 之類的選項(xiàng)以及任何用在 router-link 的 to prop 或 router.push 中的選項(xiàng)。
- next(error): (2.4.0+) 如果傳入 next 的參數(shù)是一個(gè) Error 實(shí)例,則導(dǎo)航會(huì)被終止且該錯(cuò)誤會(huì)被傳遞給 router.onError() 注冊(cè)過的回調(diào)。
最后
最終還是希望大家多看看文檔,理解了再去使用到項(xiàng)目中,不至于使用之后出現(xiàn) bug,謝謝。