总结
前话:之前也想看这个,但是因为不太自己去写原生的路由。但是最近项目中用到了,就来补坑了
history api
直接调用下面的方法你会发现你浏览器url 发生了变化 。去试试下面这个代码
history.pushState({test:1},'title',"?page1");//添加页面记录 你可测试 /page1与?page1的区别
history.replaceState({test:1},'title'),"?page1")//替换当前的页面记录 /page1与?page1的区别
有个问题是。在这个模式下。我们通过点击浏览器的前进或者后退按钮(或者代码调取前进与后退的api:History.back(),History.forward(),
History.go()
)。获取点击事件。然后会存在一个回调事件。下面这个就是回调事件。
window.addEventListener('popstate', (event) => {
console.log(event.state) // '{test:1}'通过pushState或者replaceState里面的参数 在这里取到
});
window.onpopstate = function(event) {
console.log(event.state) // '{test:1}''通过pushState或者replaceState里面的参数 在这里取到
};
总结 History.pushState()
,History.replaceState(),History.back(),History.forward(),History.go()与"popstate"与window.onpopstate 是相关联的
!!!有个很重要的是,只有History.back(),History.forward(),History.go()或者点击页面上的前进后退,才会触发
"popstate"与window.onpopstate 的函数事件。调用
History.pushState()
,History.replaceState()并不会触发"popstate"与window.onpopstate 的函数事件。这点很重要。
hash api
使用hash会值得路浏览器中url加入#。
location.href = `#${hashContent}`;//例如 hashContent =#page1 或者 page2
让调取上面的这个方法就会触发,同时点击浏览器的前后历史记录同时会调取下面的这个方法
window.addEventListener('hashchange', function(){console.log('使用了hash路由')}, false);