react-router和vue-router实现原理大同小异,都是通过两种方式,hash和history,首先看一下什么是hash和history: 1、hash模式(vue-router默认hash模式)
hash模式背后的原理是onhashchange事件。
window.onhashchange=function(){
let hash=location.hash.slice(1);
document.body.style.color=hash;
}
2.history模式
当使用history模式时,url就像正常的url,例如abc.com/user/id相比hash模式更加好看。特别注意,history模式需要后台配置支持。如果后台没有正确配置,访问时会返回404。 其中一事件触发用到了 onpopstate。
通过history api,我们丢弃了#,但是有一个缺点,当刷新时,如果服务器中没有相应的相应或者资源,会刷出一个404来(刷新需要请求服务器)。所以history模式不怕前进,不怕后退,就怕刷新。