<body>
<a href="javascript:;" data-to='/'>首頁</a>//跳空
<a href="javascript:;" data-to='/home'>home</a>
<a href="javascript:;" data-to='/index'>index</a>
<div id="view"></div>
</body>
<script>
class Router {
constructor({routes}) {
this.routes = routes;
this.bindClick();
this.init()
}
init() {
window.addEventListener('popstate', this.updataView.bind(this))
}
bindClick() {
let pushA = document.querySelectorAll('a');
[].forEach.call(pushA, item => {
item.addEventListener('click',() => {
let clickRes = item.getAttribute('data-to');
window.history.pushState({},null,clickRes);
this.updataView()
})
})
}
updataView() {
view.innerHTML = this.routes.filter(item => item.path === window.location.pathname)[0].component
}
}
new Router({
routes:[
{
path:'/',
component:'首頁'
},
{
path:'/home',
component:'home'
},
{
path:'/index',
component:'index'
}
]
})
</script>
注意:history要起靜態服務,否則會報錯