[TOC]
# 摘要
無論是 vue-router 還是 react-router,其核心都是用 hash / H5 history 實現的,這里我們拋開框架來自己實現下簡單的前端路由功能。
# hash 路由
hash 路由一個明顯的標志是帶有`#`,我們主要是通過監聽 url 中的 hash 變化來進行路由跳轉。
有以下幾個要點:
- 以鍵值對的形式存儲 path 及其回調函數
- 監聽 hashchange 事件觸發對應的回調
- 用一個 history 數組來記錄之前的 hash 路由,并創建一個指針來實現前進后退的功能
```js
class Routers {
constructor () {
// 以鍵值對的形式存儲路由
this.routes = {}
// 當前路由的 url
this.currentUrl = ''
// 記錄出現過的 hash
this.history = []
// 作為指針,默認指向 this.history 的末尾,根據后退前進指向 history 中不同的 hash
this.currentIndex = this.history.length - 1
this.isBack = false // 記錄是否為后退操作
// 監聽對應事件
this.refresh = this.refresh.bind(this)
this.backOff = this.backOff.bind(this)
window.addEventListener('load', this.refresh, false)
window.addEventListener('hashchange', this.refresh, false)
}
// 將 path 路徑與對應的 callback 函數儲存
route (path, callback) {
this.routes[path] = callback || function () {}
}
// 刷新
refresh () {
this.currentUrl = location.hash.slice(1) || '/' // 獲取當前 URL 中的 hash 路徑
if (!this.isBack) {
this.history.push(this.currentUrl) // 將當前 hash 路由推入 history 數組中
}
this.currentIndex++ // 指針向前移動
this.routes[this.currentUrl]() // 執行當前 hash 路徑的 callback 函數
this.isBack = false
}
// 后退功能
backOff () {
this.isBack = true
// 如果指針小于 0 的話就不存在對應 hash 路由了,因此鎖定指針為 0 即可
this.currentIndex <= 0 ? this.currentIndex = 0 : this.currentIndex = this.currentIndex - 1
location.hash = `#${this.history[this.currentIndex]}` // location 響應變化
this.routes[this.history[this.backOff.currentIndex]]() // 執行對應的 callback
}
}
```
# History 路由
首先 History 有以下 API,具體見 [MDN](https://developer.mozilla.org/zh-CN/docs/Web/API/History)
| 屬性 | 描述 |
| --- | --- |
| state -> window.history.state | 返回一個表示歷史堆棧頂部的狀態的值 |
| length -> window.history.length | 返回一個整數,表示會話歷史中的元素數目
| 方法 | 描述 |
| --- | --- |
| back() | 返回上一頁 |
| forward() | 在瀏覽器歷史記錄中前往下一頁 |
| go() | 參數為 -1 時前往上一頁,參數為 1 時前往下一頁 |
| pushState(stateObject, title, URL) | 按指定的名稱和 URL(如果提供該參數)將數據 push 進會話歷史棧,數據被 DOM 進行不透明處理;你可以指定任何可以被序列化的 javaScript 對象 |
| replaceState(stateObject, title, URL) | 按指定的數據、名稱和 URL(如果提供該參數)更新歷史棧上最新的入口。這個數據被 DOM 進行了不透明處理。你可以指定任何可以被序列化的 JavaScript 對象 |
| 事件 | 描述 |
| --- | --- |
| popState | 瀏覽器跳轉到新的狀態時會觸發 popState 事件,該事件將攜帶這個 stateObject 參數的副本 |
```js
class Routers {
constructor () {
this.routes = {}
this._bindPopState()
}
// 初始化路由
init (path) {
history.replaceState({ path: path }, null, path)
this.routes[path] && this.routes[path]()
}
// 將路徑和對應的回調函數加入 hashMap
route (path, callback) {
this.routes[path] = callback || function () {}
}
go (path) {
history.pushState({ path: path }, null, path)
this.routes[path] && this.routes[path]()
}
// 監聽 popstate 事件
_bindPopState () {
window.addEventListener('popstate', e => {
const path = e.state && e.state.path
this.routes[path] && this.routes[path]()
})
}
}
```
# 參考資料
[https://www.cxymsg.com/guide/router.html#%E5%89%8D%E8%A8%80](https://www.cxymsg.com/guide/router.html#%E5%89%8D%E8%A8%80)
- 序言 & 更新日志
- H5
- Canvas
- 序言
- Part1-直線、矩形、多邊形
- Part2-曲線圖形
- Part3-線條操作
- Part4-文本操作
- Part5-圖像操作
- Part6-變形操作
- Part7-像素操作
- Part8-漸變與陰影
- Part9-路徑與狀態
- Part10-物理動畫
- Part11-邊界檢測
- Part12-碰撞檢測
- Part13-用戶交互
- Part14-高級動畫
- CSS
- SCSS
- codePen
- 速查表
- 面試題
- 《CSS Secrets》
- SVG
- 移動端適配
- 濾鏡(filter)的使用
- JS
- 基礎概念
- 作用域、作用域鏈、閉包
- this
- 原型與繼承
- 數組、字符串、Map、Set方法整理
- 垃圾回收機制
- DOM
- BOM
- 事件循環
- 嚴格模式
- 正則表達式
- ES6部分
- 設計模式
- AJAX
- 模塊化
- 讀冴羽博客筆記
- 第一部分總結-深入JS系列
- 第二部分總結-專題系列
- 第三部分總結-ES6系列
- 網絡請求中的數據類型
- 事件
- 表單
- 函數式編程
- Tips
- JS-Coding
- Framework
- Vue
- 書寫規范
- 基礎
- vue-router & vuex
- 深入淺出 Vue
- 響應式原理及其他
- new Vue 發生了什么
- 組件化
- 編譯流程
- Vue Router
- Vuex
- 前端路由的簡單實現
- React
- 基礎
- 書寫規范
- Redux & react-router
- immutable.js
- CSS 管理
- React 16新特性-Fiber 與 Hook
- 《深入淺出React和Redux》筆記
- 前半部分
- 后半部分
- react-transition-group
- Vue 與 React 的對比
- 工程化與架構
- Hybird
- React Native
- 新手上路
- 內置組件
- 常用插件
- 問題記錄
- Echarts
- 基礎
- Electron
- 序言
- 配置 Electron 開發環境 & 基礎概念
- React + TypeScript 仿 Antd
- TypeScript 基礎
- React + ts
- 樣式設計
- 組件測試
- 圖標解決方案
- Storybook 的使用
- Input 組件
- 在線 mock server
- 打包與發布
- Algorithm
- 排序算法及常見問題
- 劍指 offer
- 動態規劃
- DataStruct
- 概述
- 樹
- 鏈表
- Network
- Performance
- Webpack
- PWA
- Browser
- Safety
- 微信小程序
- mpvue 課程實戰記錄
- 服務器
- 操作系統基礎知識
- Linux
- Nginx
- redis
- node.js
- 基礎及原生模塊
- express框架
- node.js操作數據庫
- 《深入淺出 node.js》筆記
- 前半部分
- 后半部分
- 數據庫
- SQL
- 面試題收集
- 智力題
- 面試題精選1
- 面試題精選2
- 問答篇
- 2025面試題收集
- Other
- markdown 書寫
- Git
- LaTex 常用命令
- Bugs