原生路由的实现
在HTML5的 history API 出现之前,前端的路由都是通过 hash 来实现的,hash 能兼容低版本的浏览器。当 url 的 hash 发生变化时,触发 hashchange 注册的回调,回调中去进行不同的操作,进行不同的内容的展示。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>路由</title>
</head>
<body>
<ul>
<li><a href="#/">默认路由</a></li>
<li><a href="#/router1">路由1</a></li>
<li><a href="#/router2">路由2</a></li>
</ul>
<div id="content"></div>
</body>
<script type="text/javascript">
class Router{
constructor(routes = {}) {
this.routes = routes;
this.curUrl = "";
}
route(path,callback){
this.routes[path] = callback || function(){
}
}
refresh(){
this.curUrl = location.hash.slice(1) || '/';
if(this.routes[this.curUrl]){
this.routes[this.curUrl]();
}else{
console.log('路由没有注册');
}
}
init(){
window.addEventListener('load', this.refresh.bind(this), false);
window.addEventListener('hashchange', this.refresh.bind(this), false);
}
}
function changeContent(text){
document.getElementById('content').innerHTML = text;
}
let router = new Router({
'/' : function(){
changeContent('默认路由');
},
'/router1':function(){
changeContent('路由1');
}
})
router.route('/router2',function(){
changeContent('路由2');
})
router.init();
</script>
</html>