vue-router之hash模式和history模式

當前版本: 3.0.3
類目錄: src/history/前端

hash模式

即地址欄 URL 中的 # 符號(此 hash 不是密碼學裏的散列運算)。好比這個 URL:http://www.abc.com/#/hello,hash 的值爲 #/hello。它的特色在於:hash 雖然出如今 URL 中,但不會被包括在 HTTP 請求中,對後端徹底沒有影響,所以改變 hash 不會從新加載頁面。vue

history模式

利用了 HTML5 History Interface 中新增的 pushState() 和 replaceState() 方法。(須要特定瀏覽器支持)這兩個方法應用於瀏覽器的歷史記錄棧,在當前已有的 back、forward、go 的基礎之上,它們提供了對歷史記錄進行修改的功能。只是當它們執行修改時,雖然改變了當前的 URL,但瀏覽器不會當即向後端發送請求。vue-router

HTML5History實現

使用window.addEventListener('popstate')監聽瀏覽器滾動行爲,而後判斷配置是否有scrollBehavior, 有就調用handleScroll方法來處理
滾動行爲: 使用前端路由,當切換到新路由時,想要頁面滾到頂部,或者是保持原先的滾動位置,就像從新加載頁面那樣。 vue-router 能作到,並且更好,它讓你能夠自定義路由切換時頁面如何滾動。後端

handleScroll瀏覽器

<!-- 等待頁面渲染完才進行滾動的操做 -->
  router.app.$nextTick(() => {
      <!-- 初始化數據 -->
    const position = getScrollPosition()
    const shouldScroll = behavior.call(router, to, from, isPop ? position : null)

    if (!shouldScroll) {
      return
    }
    <!-- 判斷是不是Promise,官網說支持異步 -->
    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)
    }
  })

scrollToPositionapp

function scrollToPosition (shouldScroll, position) {
  const isObject = typeof shouldScroll === 'object'
  <!-- 對position進行初始化的操做  -->
  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來進行滾動處理
  if (position) {
    window.scrollTo(position.x, position.y)
  }
}

push異步

push操做也是 HTML5History模式下的一個比較關鍵的方法,他使用pushState來進行跳轉操做,而後handleScroll來進行滾動\url

export function pushState (url?: string, replace?: boolean) {
    <!-- 保存當前頁面的滾動位置 -->
  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 {
      <!-- 判斷是哪一種操做動做 -->
    if (replace) {
      history.replaceState({ key: _key }, '', url)
    } else {
      _key = genKey()
      history.pushState({ key: _key }, '', url)
    }
  } catch (e) {
    window.location[replace ? 'replace' : 'assign'](url)
  }
}

HashHistory實現

對於HashHistory的實現,和HTML5History的區別是在於Listener的方式和跳轉的方式
Listener的方式這裏是使用了hashchange,可是若是須要滾動行爲就會去監聽popstatecode

window.addEventListener(supportsPushState ? 'popstate' : 'hashchange')

跳轉的方式會判斷是否須要滾動,不須要就直接使用window.location.hashorm

function pushHash (path) {
  if (supportsPushState) {
    pushState(getUrl(path))
  } else {
    window.location.hash = path
  }
}
相關文章
相關標籤/搜索