前端路由hash和history的实现原理
一、hash
-
hash的实现原理是在url后面通过拼接一串hash值来生成路由,例如
#/home,在页面的url之后拼接上就可以了 -
代码实现
<div> <!-- 两个超链接,使用hash对url进行更改 --> <a href="#/home">首页</a> <a href="#/about">关于</a> </div> <div class="routerView"> </div> <script> //监听hash的变化 window.addEventListener("hashchange",(e) => { // console.log("hashChange",location.hash,e); //在这里面可以通过loaction.hash来获取当前hash值 switch(location.hash){ case "#/home": console.log("#/home",document.getElementsByClassName("routerView")); document.getElementsByClassName("routerView")[0].innerText = "首页"; break; case "#/about": console.log("#/about",document.getElementsByClassName("routerView")); document.getElementsByClassName("routerView")[0].innerText = "关于"; } }) </script> -
讲解:通过a标签来的href属性来定义
#/home和#/about,在js当中通过监听hashchange事件来监听页面的hash变化,当发生变化的时候,我们获取到当前路由的hash,通过location.hash来获取当前页面的值,然后通过判断当前hash的值来判断应该渲染是目内容。 -
通过hash来更改路由,会导致浏览器的url当中出现
#,和真实的路由不太一样
二、history
1.基本操作
-
history是html5当中新出的API,从h5开始,允许开发者对浏览器的history线栈进行调用。可以对栈进行增删改查。
-
向后跳转
window.history.back();//这和用户点击浏览器回退按钮的效果相同 -
向前跳转
window.history.foeward();//这和用户点击浏览器前进按钮的效果相同 -
跳转到histor栈当中指定的一个页面(以当前页面为标志0,前进为1,后退为-1)
window,history.go(-1); //跳转到当前页面的上一个页面,相当于调用了back() window.history.go(1);//跳转到当前页面的前一个页面相当于调用了forward -
获取history栈长度
let numberOfEntries = window.history.length;
2.修改和添加历史记录当中的条目
-
pushState
<script> /** *给history栈添加一条历史记录 * @params state 给history当中的stateObj添加一条状态 * @params titlet 暂无意义,默认为"" * @params href 页面跳转的路由,非必要 */ window.history.pushState(state,title,href); </script> -
popState
每当活动的历史记录项发生变化时,
popstate事件都会被传递给window对象。如果当前活动的历史记录项是被pushState创建的,或者是由replaceState改变的,那么popstate事件的状态属性state会包含一个当前历史记录状态对象的拷贝。 -
replaceState
window.history.replaceState(); // 修改页面