浏览器路由模式
浏览器路由模式
-
href属性
href 属性保存当前网页的URL
# 访问百度 https://www.baidu.com/ location.href "https://www.baidu.com/" # console输出 -
hash模式
-
修改状态
# 访问百度 https://www.baidu.com/ location.hash='down' "https://www.baidu.com/#down" # console输出 -
hash模式使用
hash模式背后的原理是
onhashchange事件,可以在window对象上监听这个事件hash模式用#进行跳转控制,hash发生变化的url都会被浏览器记录下来,浏览器上的前进、后退都可以使用,并且与浏览器交互时不传递#及#以后的路径
<div id="box"></div> <a href="">青色</a>#box { width: 100px; height: 100px; background-color: rgb(208, 198, 67); }let url = window.location.href let a = document.getElementsByTagName("a")[0] a.href = url+"#cyan" console.log(window.location.href) window.onhashchange = function(event){ console.log(event.oldURL, event.newURL) let hash = location.hash.slice(1) let box = document.getElementById("box") box.style.backgroundColor = hash } -
history模式
随着history api的到来,前端路由开始进化了,前面的hashchange,你只能改变#后面的url片段,而history api则给了前端完全的自由。缺点:怕刷新,f5,(如果后端没有准备的话),因为刷新是实实在在地去请求服务器的。注意,该操作只改变url地址信息,不刷新界面。
-
切换历史状态
windows.history.go(-2); //后退两次 windows.history.go(2); //前进两次 windows.history.back(); //后退 windows.hsitory.forward(); //前进 -
修改历史状态
//向浏览器新增一条历史记录,但是不会刷新当前页面(不会重载), //state:对象,可以用作携带信息用, //title:目前来看没啥用一般为空或null, //URL:即要更改页面的URL,且必须同源,不能跨域; windows.history.pushState(state,title,URL) //更改当前浏览器的历史记录,即把当前执行此代码页面的记录给替换掉,参数同上 windows.history.replaceState(state,title,URL): -
历史信息查询
windows.history.length //历史记录数 windows.history.state //查询pushState或replaceState传入的state参数 -
历史事件
windows.onpopstate = function(event){/*...*/} //修改pushState或replaceState不触发
-

浙公网安备 33010602011771号