路由

server router

圖片描述

前端路由

https://segmentfault.com/a/11...前端

圖片描述
vue router hash 源碼vue

/**
 * 添加 url hash 變化的監聽器
 */
setupListeners () {
  const router = this.router

  /**
   * 每當 hash 變化時就解析路徑
   * 匹配路由
   */
  window.addEventListener('hashchange', () => {
    const current = this.current
    /**
     * transitionTo: 
     * 匹配路由
     * 並經過路由配置,把新的頁面 render 到 ui-view 的節點
     */
    this.transitionTo(getHash(), route => {
      replaceHash(route.fullPath)
    })
  })
}

vue router history 源碼react

export class HTML5History extends History {
  constructor (router, base) {
    super(router, base)
    /**
     * 原理仍是跟 hash 實現同樣
     * 經過監聽 popstate 事件
     * 匹配路由,而後更新頁面 DOM
     */
    window.addEventListener('popstate', e => {
      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 === initLocation) {
        return
      }

      this.transitionTo(location, route => {
        if (supportsScroll) {
          handleScroll(router, route, current, true)
        }
      })
    })
  }

  go (n) {
    window.history.go(n)
  }

  push (location, onComplete, onAbort) {
    const { current: fromRoute } = this
    this.transitionTo(location, route => {
      // 使用 pushState 更新 url,不會致使瀏覽器發送請求,從而不會刷新頁面
      pushState(cleanPath(this.base + route.fullPath))
      onComplete && onComplete(route)
    }, onAbort)
  }

  replace (location, onComplete, onAbort) {
    const { current: fromRoute } = this
    this.transitionTo(location, route => {
      // replaceState 跟 pushState 的區別在於,不會記錄到歷史棧
      replaceState(cleanPath(this.base + route.fullPath))
      onComplete && onComplete(route)
    }, onAbort)
  }
}

react-native router

相關文章
相關標籤/搜索