实现路由(简易版)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// hash路由
class Route{
 constructor(){
   // 路由存储对象
   this.routes = {}
   // 当前hash
   this.currentHash = ''
   // 绑定this,避免监听时this指向改变
   this.freshRoute = this.freshRoute.bind(this)
   // 监听
   window.addEventListener('load', this.freshRoute, false)
   window.addEventListener('hashchange', this.freshRoute, false)
}
 // 存储
 storeRoute (path, cb) {
   this.routes[path] = cb || function () {}
}
 // 更新
 freshRoute () {
   this.currentHash = location.hash.slice(1) || '/'
   this.routes[this.currentHash]()
}
}