<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>history route</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.slim.js"></script>
</head>
<body>
<ul>
<li>电影</li>
<li>影院</li>
</ul>
<div id='content'></div>
<script>
let comp = [
{
path:'/movie',
component:'<div>comp1</div>'
},
{
path:'/test',
component:'<div>comp2</div>'
}
]
// 给li标签添加点击事件
$('li').on('click',function() {
let {path,component} = comp[$(this).index()]
history.pushState({id:0},'movie',path)
render(component)
// 拿到参数
let state = history.state
console.log(state);
})
function render(component){
$('#content').html(component)
}
// 监听hash是否发生变化,截取变化的长度对比然后根据结果操控dom
$(window).on('load',()=>{
history.pushState({id:0},'movie111','/movie')
render(comp[0].component)
})
// 只能检测到前进后退
$(window).on('popstate',()=>{
// 拿到参数
let state = history.state
console.log(state);
let pathname = location.pathname
let {component} = comp.find(v=>v.path === pathname)
render(component)
})
</script>
</body>
</html>