这里要注意有一个坑,就是history模式天然是要服务器支持的,也就是说至少也需要起一个服务器。不然“///”这种样式的路径是不会识别的。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<a href="/about">about</a>
<a href="/">home</a>
<a href="/test">test</a>
<a href="/about/test">about_test</a>
<div id="app"></div>
<script type="text/javascript">
function Router(routeOption,id){
this.routes=routeOption;
this.currentRoute = '';
this.dom = id ? document.getElementById(id) : null;
}
Router.prototype = {
init(){
window.addEventListener('popstate', () => {
this.currentRoute = window.location.pathname;
this.routes[this.currentRoute]
? this.dom ? this.dom.innerText = this.routes[this.currentRoute] : null
: null;
})
},
_updateState(route){
window.history.pushState(
null,
this.routes[route],
route
)
},
route(route){
this._updateState(route);
}
}
let router = new Router({
'/': 'Home',
'/about': 'About',
'/about/test': 'About_test'
},'app');
router.init();
document.querySelectorAll('a').forEach(function(item,index){
item.addEventListener('click',function(e){
e.preventDefault();
let route = item.getAttribute('href');
router.route(route);
})
})
</script>
</body>
</html>