Skip to main content

手写路由

//  Hash 路由
class Router {
constructor {
this.routes = {}
this.init();
}

refresh() {
// 获取第一个路由,并执行刷新页面
this.curUrl = location.hash.slice(1) || '/';
this.routes[this.curUrl]();
}

// 添加路由
route(path, callback) {
this.routes[path] = callback || function(){};
}

init() {
window.addEventListener('load', this.refresh.bind(this), false);
window.addEventListener('hashchange', this.refresh.bind(this), false);
}
}
// history 路由
class Router {
constructor {
// History.back()
// History.forward()
// History.go(n)
// history.pushState()
// history.replaceState()
}
}

参考