<body>
<a href="#/">主页</a>
<a href="#/index">index</a>
<a href="#/home">home</a>
<div id="view"></div>
</body>
<script>
class Router{
constructor({routes}) {
this.routes = routes;
this.init();
this.everyPath = {};
this.routes.forEach(item => {
this.everyPath[item.path] = function() {
document.querySelector('#view').innerHTML = item.component
}
})
}
init() {
window.addEventListener('hashchange',this.updateLocation.bind(this))
window.addEventListener('load',this.updateLocation.bind(this));
}
updateLocation() {
this.everyPath[window.location.hash.slice(1)]()
}
}
new Router({
routes:[{
path:'/',
component:'主页'
}, {
path:'/index',
component:'index'
}, {
path:'/home',
component:'home'
}]
})
</script>
原生实现hash路由匹配机制
最新推荐文章于 2022-05-22 16:31:50 发布