hashRouter and BrowserRouter

<html>
<body>

<div>
<button class="btn" onclick="btnFun();">点击新增一条历史记录</button>
</div>
<script>
var num=0;
console.log('增加历史记录前 state的值:',history.state,navigator,history,screen,location,document); // null
function btnFun() {//点击事件
// 增加一个历史记录
history.pushState(`我是记录num:${num}`,null,'html5.html?b=1');
num++;
console.log('增加历史记录后 state的值:',history.state); // a
};
window.addEventListener('popstate',function() {
var state = history.state;//取出state值
//注意:在此处时(点击后退按钮时),state的值已经为null
// (因为返回时历史记录会被删除,浏览器动作)
console.log('点击后退按钮后 state的值:',navigator,history,screen,location,document); // null
//判断,想要执行的操作

});
</script>

<a href="#/home">home</a>
<a href="#/index">index</a>
<a href="#/other">other</a>
<div id="box"></div>
<script>
window.onhashchange = function(){
var hash = window.location.hash.slice(1)
var box = document.getElementById('box')
if(hash=='/home'){
box.innerHTML = "home"
}else if(hash=='/index'){
box.innerHTML = "index"
}else{
box.innerHTML = "default"
}
}
</script>

</body>
</html>

原文地址:https://www.cnblogs.com/qiqi105/p/9003553.html