前面已經實作h5的history路由跳轉,這里是另一種哈西路由
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<a href="#/">首頁</a>
<a href="#/home">home</a>
<a href="#/about">about</a>
<div id="root"></div>
</div>
</body>
<script>
class Router {
constructor({route}) {
this.route = route;
this.root = document.getElementById('root');
this.init()
}
init() {
// hashchange事件監聽url#/的變化
window.addEventListener('hashchange', () => {
let topath = window.location.hash.slice(1)
this.updateDom(topath)
})
// 監聽瀏覽器重繪
window.addEventListener('load', () => {
let topath = window.location.hash.slice(1);
this.updateDom(topath)
})
}
updateDom(topath) {
let Iner = this.route.filter(item => item.path === topath)[0].component;
this.root.innerHTML = Iner
}
}
new Router({
route: [
{
path: '/',
component: '首頁'
},
{
path: '/home',
component: 'home'
},
{
path: '/about',
component: 'about'
}
]
})
</script>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/200417.html
標籤:其他
下一篇:es客戶端執行緒池配置
