<a href="#/menu" data-href="/menu">menu<a>
<div class="targetNode"></div>
history 模式
class historyRouter{
constructor(){
this.currentPath = '/';
this.router = {};
}
init(){
window.addEventListener("DOMContentLoaded",this.updateView.bind(this,'/'));
var that = this;
window.addEventListener('click', function (ev) {
if(ev.target.tagName.toLocaleLowerCase() === 'a' && ev.target.getAttribute('data-href')) {
ev.preventDefault();
var path = ev.target.getAttribute('data-href');
history.pushState({ path: path }, '', path)
that.updateView(path)
}
})
window.addEventListener('popstate', function (ev) {
if(ev.state){
var path = ev.state.path
that.updateView(path)
}else{
that.updateView('/')
}
})
}
route(path,calback){
this.router[path] = calback;
}
updateView(path){
this.currentPath = path
this.router[this.currentPath] && this.router[this.currentPath]()
}
}
hash 模式
function HashRouter(){
this.currentPath = '/';
this.router = {};
}
HashRouter.prototype = {
init: function (){
window.addEventListener('DOMContentLoaded', this.updateView.bind(this))
window.addEventListener('hashchange', this.updateView.bind(this))
},
route: function(path,calback){
this.router[path] = calback;
},
updateView:function(){
this.currentPath = location.hash.substring(1) || '/',
this.router[this.currentPath] && this.router[this.currentPath]();
}
}
let route = new HashRouter();
route.init()
route.route("/menu",function(){
let target = document.querySelector(".targetNode");
target.innerHTML = 'test'
})