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