前端路由簡介以及vue-router實現原理


后端路由簡介

路由這個概念最先是后端出現的。在以前用模板引擎開發頁面時,經常會看到這樣

http://www.xxx.com/login

大致流程可以看成這樣:

  1. 瀏覽器發出請求

  2. 服務器監聽到80端口(或443)有請求過來,並解析url路徑

  3. 根據服務器的路由配置,返回相應信息(可以是 html 字串,也可以是 json 數據,圖片等)

  4. 瀏覽器根據數據包的 Content-Type 來決定如何解析數據

簡單來說路由就是用來跟后端服務器進行交互的一種方式,通過不同的路徑,來請求不同的資源,請求不同的頁面是路由的其中一種功能。

前端路由

1. hash 模式

隨着 ajax 的流行,異步數據請求交互運行在不刷新瀏覽器的情況下進行。而異步交互體驗的更高級版本就是 SPA —— 單頁應用。單頁應用不僅僅是在頁面交互是無刷新的,連頁面跳轉都是無刷新的,為了實現單頁應用,所以就有了前端路由。
類似於服務端路由,前端路由實現起來其實也很簡單,就是匹配不同的 url 路徑,進行解析,然后動態的渲染出區域 html 內容。但是這樣存在一個問題,就是 url 每次變化的時候,都會造成頁面的刷新。那解決問題的思路便是在改變 url 的情況下,保證頁面的不刷新。在 2014 年之前,大家是通過 hash 來實現路由,url hash 就是類似於:

http://www.xxx.com/#/login

這種 #。后面 hash 值的變化,並不會導致瀏覽器向服務器發出請求,瀏覽器不發出請求,也就不會刷新頁面。另外每次 hash 值的變化,還會觸發hashchange 這個事件,通過這個事件我們就可以知道 hash 值發生了哪些變化。然后我們便可以監聽hashchange來實現更新頁面部分內容的操作:

function matchAndUpdate () {
   // todo 匹配 hash 做 dom 更新操作
}

window.addEventListener('hashchange', matchAndUpdate)

2. history 模式

14年后,因為HTML5標准發布。多了兩個 API,pushStatereplaceState,通過這兩個 API 可以改變 url 地址且不會發送請求。同時還有 popstate 事件。通過這些就能用另一種方式來實現前端路由了,但原理都是跟 hash 實現相同的。用了 HTML5 的實現,單頁路由的 url 就不會多出一個#,變得更加美觀。但因為沒有 # 號,所以當用戶刷新頁面之類的操作時,瀏覽器還是會給服務器發送請求。為了避免出現這種情況,所以這個實現需要服務器的支持,需要把所有路由都重定向到根頁面。

function matchAndUpdate () {
   // todo 匹配路徑 做 dom 更新操作
}

window.addEventListener('popstate', matchAndUpdate)

Vue router 實現

我們來看一下vue-router是如何定義的:

import VueRouter from 'vue-router'
Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

new Vue({
  router
  ...
})

可以看出來vue-router是通過 Vue.use的方法被注入進 Vue 實例中,在使用的時候我們需要全局用到 vue-routerrouter-viewrouter-link組件,以及this.$router/$route這樣的實例對象。那么是如何實現這些操作的呢?下面我會分幾個章節詳細的帶你進入vue-router的世界。

vue-router 實現 -- install

vue-router 實現 -- new VueRouter(options)

vue-router 實現 -- HashHistory

vue-router 實現 -- HTML5History

vue-router 實現 -- 路由變更監聽

造輪子 -- 動手實現一個數據驅動的 router

經過上面的闡述,相信您已經對前端路由以及vue-router有了一些大致的了解。那么這里我們為了貫徹無解肥,我們來手把手擼一個下面這樣的數據驅動的 router

new Router({
  id: 'router-view', // 容器視圖
  mode: 'hash', // 模式
  routes: [
    {
      path: '/',
      name: 'home',
      component: '<div>Home</div>',
      beforeEnter: (next) => {
        console.log('before enter home')
        next()
      },
      afterEnter: (next) => {
        console.log('enter home')
        next()
      },
      beforeLeave: (next) => {
        console.log('start leave home')
        next()
      }
    },
    {
      path: '/bar',
      name: 'bar',
      component: '<div>Bar</div>',
      beforeEnter: (next) => {
        console.log('before enter bar')
        next()
      },
      afterEnter: (next) => {
        console.log('enter bar')
        next()
      },
      beforeLeave: (next) => {
        console.log('start leave bar')
        next()
      }
    },
    {
      path: '/foo',
      name: 'foo',
      component: '<div>Foo</div>'
    }
  ]
})

思路整理

首先是數據驅動,所以我們可以通過一個route對象來表述當前路由狀態,比如:

current = {
    path: '/', // 路徑
    query: {}, // query
    params: {}, // params
    name: '', // 路由名
    fullPath: '/', // 完整路徑
    route: {} // 記錄當前路由屬性
}

current.route內存放當前路由的配置信息,所以我們只需要監聽current.route的變化來動態render頁面便可。

接着我么需要監聽不同的路由變化,做相應的處理。以及實現hashhistory模式。

數據驅動

這里我們延用vue數據驅動模型,實現一個簡單的數據劫持,並更新視圖。首先定義我們的observer

class Observer {
  constructor (value) {
    this.walk(value)
  }

  walk (obj) {
    Object.keys(obj).forEach((key) => {
      // 如果是對象,則遞歸調用walk,保證每個屬性都可以被defineReactive
      if (typeof obj[key] === 'object') {
        this.walk(obj[key])
      }
      defineReactive(obj, key, obj[key])
    })
  }
}

function defineReactive(obj, key, value) {
  let dep = new Dep()
  Object.defineProperty(obj, key, {
    get: () => {
      if (Dep.target) {
        // 依賴收集
        dep.add()
      }
      return value
    },
    set: (newValue) => {
      value = newValue
      // 通知更新,對應的更新視圖
      dep.notify()
    }
  })
}

export function observer(value) {
  return new Observer(value)
}

再接着,我們需要定義DepWatcher:

export class Dep {
  constructor () {
    this.deppend = []
  }
  add () {
    // 收集watcher
    this.deppend.push(Dep.target)
  }
  notify () {
    this.deppend.forEach((target) => {
      // 調用watcher的更新函數
      target.update()
    })
  }
}

Dep.target = null

export function setTarget (target) {
  Dep.target = target
}

export function cleanTarget() {
  Dep.target = null
}

// Watcher
export class Watcher {
  constructor (vm, expression, callback) {
    this.vm = vm
    this.callbacks = []
    this.expression = expression
    this.callbacks.push(callback)
    this.value = this.getVal()

  }
  getVal () {
    setTarget(this)
    // 觸發 get 方法,完成對 watcher 的收集
    let val = this.vm
    this.expression.split('.').forEach((key) => {
      val = val[key]
    })
    cleanTarget()
    return val
  }

  // 更新動作
  update () {
    this.callbacks.forEach((cb) => {
      cb()
    })
  }
}

到這里我們實現了一個簡單的訂閱-發布器,所以我們需要對current.route做數據劫持。一旦current.route更新,我們可以及時的更新當前頁面:

  // 響應式數據劫持
  observer(this.current)

  // 對 current.route 對象進行依賴收集,變化時通過 render 來更新
  new Watcher(this.current, 'route', this.render.bind(this))

恩....到這里,我們似乎已經完成了一個簡單的響應式數據更新。其實render也就是動態的為頁面指定區域渲染對應內容,這里只做一個簡化版的render:

  render() {
    let i
    if ((i = this.history.current) && (i = i.route) && (i = i.component)) {
      document.getElementById(this.container).innerHTML = i
    }
  }

hash 和 history

接下來是hashhistory模式的實現,這里我們可以沿用vue-router的思想,建立不同的處理模型便可。來看一下我實現的核心代碼:

this.history = this.mode === 'history' ? new HTML5History(this) : new HashHistory(this)

當頁面變化時,我們只需要監聽hashchangepopstate事件,做路由轉換transitionTo:

  /**
   * 路由轉換
   * @param target 目標路徑
   * @param cb 成功后的回調
   */
  transitionTo(target, cb) {
    // 通過對比傳入的 routes 獲取匹配到的 targetRoute 對象
    const targetRoute = match(target, this.router.routes)
    this.confirmTransition(targetRoute, () => {
      // 這里會觸發視圖更新
      this.current.route = targetRoute
      this.current.name = targetRoute.name
      this.current.path = targetRoute.path
      this.current.query = targetRoute.query || getQuery()
      this.current.fullPath = getFullPath(this.current)
      cb && cb()
    })
  }

  /**
   * 確認跳轉
   * @param route
   * @param cb
   */
  confirmTransition (route, cb) {
    // 鈎子函數執行隊列
    let queue = [].concat(
      this.router.beforeEach,
      this.current.route.beforeLeave,
      route.beforeEnter,
      route.afterEnter
    )
    
    // 通過 step 調度執行
    let i = -1
    const step = () => {
      i ++
      if (i > queue.length) {
        cb()
      } else if (queue[i]) {
        queue[i](step)
      } else {
        step()
      }

    }
    step(i)
  }
}

這樣我們一方面通過this.current.route = targetRoute達到了對之前劫持數據的更新,來達到視圖更新。另一方面我們又通過任務隊列的調度,實現了基本的鈎子函數beforeEachbeforeLeavebeforeEnterafterEnter
到這里其實也就差不多了,接下來我們順帶着實現幾個API吧:

  /**
   * 跳轉,添加歷史記錄
   * @param location 
   * @example this.push({name: 'home'})
   * @example this.push('/')
   */
  push (location) {
    const targetRoute = match(location, this.router.routes)

    this.transitionTo(targetRoute, () => {
      changeUrl(this.router.base, this.current.fullPath)
    })
  }

  /**
   * 跳轉,添加歷史記錄
   * @param location
   * @example this.replaceState({name: 'home'})
   * @example this.replaceState('/')
   */
  replaceState(location) {
    const targetRoute = match(location, this.router.routes)

    this.transitionTo(targetRoute, () => {
      changeUrl(this.router.base, this.current.fullPath, true)
    })
  }

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

  function changeUrl(path, replace) {
    const href = window.location.href
    const i = href.indexOf('#')
    const base = i >= 0 ? href.slice(0, i) : href
    if (replace) {
      window.history.replaceState({}, '', `${base}#/${path}`)
    } else {
      window.history.pushState({}, '', `${base}#/${path}`)
    }
  }

到這里也就基本上結束了。源碼地址:

動手擼一個 router

有興趣可以自己玩玩。實現的比較粗陋,如有疑問,歡迎指點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM