當(dāng)前版本: 3.0.3
類(lèi)目錄: src/history/base.js
hash模式
即地址欄 URL 中的 # 符號(hào)(此 hash 不是密碼學(xué)里的散列運(yùn)算)。比如這個(gè) URL: http://www.abc.com/#/hello ,hash 的值為 #/hello。它的特點(diǎn)在于:hash 雖然出現(xiàn)在 URL 中,但不會(huì)被包括在 HTTP 請(qǐng)求中,對(duì)后端完全沒(méi)有影響,因此改變 hash 不會(huì)重新加載頁(yè)面。
history模式
利用了 HTML5 History Interface 中新增的 pushState() 和 replaceState() 方法。(需要特定瀏覽器支持)這兩個(gè)方法應(yīng)用于瀏覽器的歷史記錄棧,在當(dāng)前已有的 back、forward、go 的基礎(chǔ)之上,它們提供了對(duì)歷史記錄進(jìn)行修改的功能。只是當(dāng)它們執(zhí)行修改時(shí),雖然改變了當(dāng)前的 URL,但瀏覽器不會(huì)立即向后端發(fā)送請(qǐng)求。
HTML5History實(shí)現(xiàn)
使用window.addEventListener('popstate')監(jiān)聽(tīng)瀏覽器滾動(dòng)行為,然后判斷配置是否有scrollBehavior, 有就調(diào)用handleScroll方法來(lái)處理
滾動(dòng)行為: 使用前端路由,當(dāng)切換到新路由時(shí),想要頁(yè)面滾到頂部,或者是保持原先的滾動(dòng)位置,就像重新加載頁(yè)面那樣。 vue-router 能做到,而且更好,它讓你可以自定義路由切換時(shí)頁(yè)面如何滾動(dòng)。
handleScroll
<!-- 等待頁(yè)面渲染完才進(jìn)行滾動(dòng)的操作 --> router.app.$nextTick(() => { <!-- 初始化數(shù)據(jù) --> const position = getScrollPosition() const shouldScroll = behavior.call(router, to, from, isPop ? position : null) if (!shouldScroll) { return } <!-- 判斷是否是Promise,官網(wǎng)說(shuō)支持異步 --> if (typeof shouldScroll.then === 'function') { shouldScroll.then(shouldScroll => { scrollToPosition((shouldScroll: any), position) }).catch(err => { if (process.env.NODE_ENV !== 'production') { assert(false, err.toString()) } }) } else { scrollToPosition(shouldScroll, position) } })scrollToPosition
function scrollToPosition (shouldScroll, position) { const isObject = typeof shouldScroll === 'object' <!-- 對(duì)position進(jìn)行初始化的操作 --> if (isObject && typeof shouldScroll.selector === 'string') { const el = document.querySelector(shouldScroll.selector) if (el) { let offset = shouldScroll.offset && typeof shouldScroll.offset === 'object' ? shouldScroll.offset : {} offset = normalizeOffset(offset) position = getElementPosition(el, offset) } else if (isValidPosition(shouldScroll)) { position = normalizePosition(shouldScroll) } } else if (isObject && isValidPosition(shouldScroll)) { position = normalizePosition(shouldScroll) } 使用window.scrollTo來(lái)進(jìn)行滾動(dòng)處理 if (position) { window.scrollTo(position.x, position.y) }}push
push操作也是 HTML5History模式下的一個(gè)比較關(guān)鍵的方法,他使用pushState來(lái)進(jìn)行跳轉(zhuǎn)操作,然后handleScroll來(lái)進(jìn)行滾動(dòng)/
export function pushState (url?: string, replace?: boolean) { <!-- 保存當(dāng)前頁(yè)面的滾動(dòng)位置 --> saveScrollPosition() // try...catch the pushState call to get around Safari // DOM Exception 18 where it limits to 100 pushState calls const history = window.history try { <!-- 判斷是哪種操作動(dòng)作 --> if (replace) { history.replaceState({ key: _key }, '', url) } else { _key = genKey() history.pushState({ key: _key }, '', url) } } catch (e) { window.location[replace ? 'replace' : 'assign'](url) }}
新聞熱點(diǎn)
疑難解答
圖片精選