vue-roter有3種模式:1、hash模式,用URL hash值來(lái)做路由,支持所有瀏覽器;該模式實(shí)現(xiàn)的路由,在通過(guò)鏈接后面添加““#”+路由名字”。2、history模式,由h5提供的history對(duì)象實(shí)現(xiàn),依賴(lài)H5 History API和服務(wù)器配置。3、abstract模式,支持所有JS運(yùn)行環(huán)境,如Node服務(wù)器端,如果發(fā)現(xiàn)沒(méi)有瀏覽器的API,路由會(huì)自動(dòng)強(qiáng)制進(jìn)入該模式。
本教程操作環(huán)境:windows7系統(tǒng)、vue3版,DELL G3電腦。
Vue-router 是vue框架的路由插件。
vue-roter有幾種模式
根據(jù)vue-router官網(wǎng),我們可以明確看到vue-router的mode值有3種
-
hash
-
history
-
abstract
其中,hash 和 history 是 SPA 單頁(yè)應(yīng)用程序的基礎(chǔ)。
先說(shuō)結(jié)論: spa應(yīng)用路由有2種模式,hash 和 history,vue路由有3種模式,比 spa 多了一個(gè) abstract。
源碼分析
在vue-router中通過(guò)mode這個(gè)參數(shù)修改路由的模式:
const router = new VueRouter({ mode: 'history', routes: [...] })
具體怎么實(shí)現(xiàn)的呢,首先我們下載 vue-router 的源碼
抽離出來(lái)對(duì)mode的處理
class vueRouter { constructor(options) { let mode = options.mode || 'hash' this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false if (this.fallback) { mode = 'hash' } if (!inBrowser) { mode = 'abstract' } this.mode = mode switch (mode) { case 'history': this.history = new HTML5History(this, options.base) break case 'hash': this.history = new HashHistory(this, options.base, this.fallback) break case 'abstract': this.history = new AbstractHistory(this, options.base) break default: if (process.env.NODE_ENV !== 'production') { assert(false, `invalid mode: ${mode}`) } } } }
可以看到默認(rèn)使用的是 hash 模式,當(dāng)設(shè)置為 history 時(shí),如果不支持 history 方法,也會(huì)強(qiáng)制使用 hash 模式。 當(dāng)不在瀏覽器環(huán)境,比如 node 中時(shí),直接強(qiáng)制使用 abstract 模式。
hash模式
閱讀這部分源碼前,我們先來(lái)了解下 hash 的基礎(chǔ): 根據(jù)MDN上的介紹,Location 接口的 hash 屬性返回一個(gè) USVString,其中會(huì)包含URL標(biāo)識(shí)中的 '#' 和 后面URL片段標(biāo)識(shí)符,'#' 和后面URL片段標(biāo)識(shí)符被稱(chēng)為 hash。 它有這樣一些特點(diǎn):
-
在第一個(gè)#后面出現(xiàn)的任何字符,都會(huì)被瀏覽器解讀為位置標(biāo)識(shí)符。這意味著,這些字符都不會(huì)被發(fā)送到服務(wù)器端。
-
單單改變#后的部分,瀏覽器只會(huì)滾動(dòng)到相應(yīng)位置,不會(huì)重新加載網(wǎng)頁(yè)。
-
每一次改變#后的部分,都會(huì)在瀏覽器的訪(fǎng)問(wèn)歷史中增加一個(gè)記錄,使用"后退"按鈕,就可以回到上一個(gè)位置。
-
可通過(guò)window.location.hash屬性讀取 hash 值,并且 window.location.hash 這個(gè)屬性可讀可寫(xiě)。
-
使用 window.addEventListener("hashchange", fun) 可以監(jiān)聽(tīng) hash 的變化
了解了這些基本知識(shí)后,我們繼續(xù)來(lái)看 vue-router 源碼對(duì) /src/history/hash.js 的處理
const handleRoutingEvent = () => { const current = this.current if (!ensureSlash()) { return } this.transitionTo(getHash(), route => { if (supportsScroll) { handleScroll(this.router, route, current, true) } if (!supportsPushState) { replaceHash(route.fullPath) } }) } const eventType = supportsPushState ? 'popstate' : 'hashchange' window.addEventListener( eventType, handleRoutingEvent ) this.listeners.push(() => { window.removeEventListener(eventType, handleRoutingEvent) })
首先也是使用 window.addEventListener("hashchange", fun) 監(jiān)聽(tīng)路由的變化,然后使用 transitionTo 方法更新視圖
push (location: RawLocation, onComplete?: Function, onAbort?: Function) { const { current: fromRoute } = this this.transitionTo( location, route => { pushHash(route.fullPath) handleScroll(this.router, route, fromRoute, false) onComplete && onComplete(route) }, onAbort ) } replace (location: RawLocation, onComplete?: Function, onAbort?: Function) { const { current: fromRoute } = this this.transitionTo( location, route => { replaceHash(route.fullPath) handleScroll(this.router, route, fromRoute, false) onComplete && onComplete(route) }, onAbort ) }
vue-router 的2個(gè)主要API push 和 replace 也是簡(jiǎn)單處理了下 hash , 然后調(diào)用 transitionTo 方法更新視圖
history模式
老規(guī)矩,先來(lái)了解下 HTML5History 的的基本知識(shí): 根據(jù)MDN上的介紹,History 接口允許操作瀏覽器的曾經(jīng)在標(biāo)簽頁(yè)或者框架里訪(fǎng)問(wèn)的會(huì)話(huà)歷史記錄。 使用 back(), forward()和 go() 方法來(lái)完成在用戶(hù)歷史記錄中向后和向前的跳轉(zhuǎn)。 HTML5引入了 history.pushState() 和 history.replaceState() 方法,它們分別可以添加和修改歷史記錄條目。 稍微了解下 history.pushState():
window.onpopstate = function(e) { alert(2); } let stateObj = { foo: "bar", }; history.pushState(stateObj, "page 2", "bar.html");
這將使瀏覽器地址欄顯示為 mozilla.org/bar.html
,但并不會(huì)導(dǎo)致瀏覽器加載 bar.html ,甚至不會(huì)檢查bar.html 是否存在。 也就是說(shuō),雖然瀏覽器 URL 改變了,但不會(huì)立即重新向服務(wù)端發(fā)送請(qǐng)求,這也是 spa應(yīng)用 更新視圖但不 重新請(qǐng)求頁(yè)面的基礎(chǔ)。 接著我們繼續(xù)看 vue-router 源碼對(duì) /src/history/html5.js 的處理:
const handleRoutingEvent = () => { const current = this.current // Avoiding first `popstate` event dispatched in some browsers but first // history route not updated since async guard at the same time. const location = getLocation(this.base) if (this.current === START && location === this._startLocation) { return } this.transitionTo(location, route => { if (supportsScroll) { handleScroll(router, route, current, true) } }) } window.addEventListener('popstate', handleRoutingEvent) this.listeners.push(() => { window.removeEventListener('popstate', handleRoutingEvent) })
處理邏輯和 hash 相似,使用 window.addEventListener("popstate", fun) 監(jiān)聽(tīng)路由的變化,然后使用 transitionTo 方法更新視圖。 push 和 replace 等方法就不再詳細(xì)介紹。
abstract模式
最后我們直接來(lái)看一下對(duì) /src/history/abstract.js 的處理:
constructor (router: Router, base: ?string) { super(router, base) this.stack = [] this.index = -1 }
首先定義了2個(gè)變量,stack 來(lái)記錄調(diào)用的記錄, index 記錄當(dāng)前的指針位置
push (location: RawLocation, onComplete?: Function, onAbort?: Function) { this.transitionTo( location, route => { this.stack = this.stack.slice(0, this.index + 1).concat(route) this.index++ onComplete && onComplete(route) }, onAbort ) } replace (location: RawLocation, onComplete?: Function, onAbort?: Function) { this.transitionTo( location, route => { this.stack = this.stack.slice(0, this.index).concat(route) onComplete && onComplete(route) }, onAbort ) }
push 和 replac方法 也是通過(guò) stack 和 index 2個(gè)變量,模擬出瀏覽器的歷史調(diào)用記錄。
總結(jié)
終于到了最后的總結(jié)階段了:
-
hash 和 history 的使用方式差不多,hash 中路由帶 # ,但是使用簡(jiǎn)單,不需要服務(wù)端配合,站在技術(shù)角度講,這個(gè)是配置最簡(jiǎn)單的模式,本人感覺(jué)這也是 hash 被設(shè)為默認(rèn)模式的原因
-
history 模式需要服務(wù)端配合處理404的情況,但是路由中不帶 # ,比 hash 美觀一點(diǎn)。
-
abstract 模式支持所有JavaScript運(yùn)行環(huán)境,如Node.js服務(wù)器端,如果發(fā)現(xiàn)沒(méi)有瀏覽器的API,路由會(huì)自動(dòng)強(qiáng)制進(jìn)入這個(gè)模式。
abstract 模式?jīng)]有使用瀏覽器api,可以放到node環(huán)境或者桌面應(yīng)用中,是對(duì) spa應(yīng)用 的兜底和能力擴(kuò)展。
【相關(guān)視頻教程推薦:vue視頻教程、web前端入門(mén)】