<!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 id="box">
<div>
<a href="javascript:;" data-path='/home'>home</a>
<a href="javascript:;" data-path="/show">show</a>
</div>
<div id="root"></div>
</div>
<script>
// h5 history路由
class Router {
constructor({ route }) {
this.route = route;
this.root = document.getElementById('root');
this.init()
this.towindow()
}
init() {
let as = document.querySelectorAll('a');
as.forEach(item => {
item.addEventListener('click', () => {
// 获取自定义属性
let pathChild = item.getAttribute('data-path');
// 对浏览器添加添加相应记录
window.history.pushState({}, null, pathChild);
let linePath = window.location.pathname;
this.updatePath(linePath)
})
})
}
towindow() {
// 监控浏览器刷新
window.addEventListener('load', () => {
const linePath = window.location.pathname;
this.updatePath(linePath)
})
// 监控前进后退
window.addEventListener('popstate', () => {
const linePath = window.location.pathname;
this.updatePath(linePath)
})
}
updatePath(linePath) {
const Iner = this.route.filter(item => item.path === linePath)[0].content;
this.root.innerHTML = Iner;
}
}
new Router({
route: [
{
path: '/home',
content: 'my is a home'
},
{
path: '/show',
content: 'you are a show'
}
]
});
</script>
</body>
</html>
h5 实现history路由跳转
最新推荐文章于 2024-05-06 09:24:26 发布