直奔主题
前端路由实现原理
- history Api
实现的原理 核心 api
- api
history.pushState history.replaceState - 参数
window.history.pushState(null, null, "url")
// 第一个参数 状态对象
// 第二个参数 是网页title
// 跳转路径
- hash
实现原理 核心 api
- api
hashchange 事件
锚点
实现简易路由 MyRouter
function MyRouter () {
this.routers = {}
this.currentPath = ''
}
MyRouter.prototype.router = function(path, cb) {
this.routes[path] = cb || function () {}
}
MyRouter.prototype.refresh = function() {
this.currentPath = location.hash.slice(1) || '/'
this.routes[this.currentPath]()
}
MyRouter.prototype.init = function() {
window.addEventListener('hashchange', this.refresh.bind(this), false)
window.addEventListener('load',