前端路由之——History

前面我们讲了前端路由之——hash的方法,今天我们来讨论一下前端路由的另一种方式——History ヽ(✿゚▽゚)ノ

没有看上一篇文章的小伙伴可以返回查看我们的历史文章~~

首先我们来说一下这个history是个啥嘞 ?

js的history对象


  • window.history 表示window对象的历史记录

       1.window.history.back(),后退
    
      2.window.history.forward(),前进
    
      3.window.history.go(num),前进或后退指定数量历史记录
    
  • history.pushState() 方法向浏览器历史添加了一个状态。

      pushState()方法带有三个参数:一个状态对象、一个标题(现在被忽略了)以及一个可选的URL地址
      
      history.pushState(state, title, url);
    
  • window.history.replaceState(),修改当前的 history 实体。

       history.replaceState方法的参数与pushState方法一模一样,不同之处在于replaceState()方法会修改当前历史记录条目而并非创建新的条目
    
  • popstate 事件,history 实体改变时触发的事件。

  • window.history.state,会获得 history 实体中的 state 对象。

上面介绍的 pushStatereplaceState是一个HTML5的新接口,他们的作用非常大,可以做到改变网址却不需要刷新页面,下面我们来详细了解一下 ~~

详细了解


pushState方法

接受三个参数,依次为:

state:一个与指定网址相关的状态对象,popstate事件触发时,该对象会传入回调函数。如果不需要这个对象,此处可以填null。

title:新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null。

url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。

最常用的方法:window.history.pushState(null,null,'download?id=1');

完整使用:var oState= {title: '下载' };window.history.pushState(oState, '下载', 'download?id=1');

replaceState方法

和pushState原理一样使用也一样:

最常用的方法:window.history.replaceState(null,null,'download?id=1');

完整使用:var oState= {title: '下载' };window.history.replaceState(oState, '下载', 'download?id=1');

  • 特点:replaceState不会加入到历史记录里面,用history.go(-1)会跳过当前页面相当于是history.go(-2)。

栗子来了~


<!DOCTYPE HTML>
<!-- this starts off as http://example.com/line?x=5 -->
<title>Line Game - 5</title>
<p>You are at coordinate <span id="coord">5</span> on the line.</p>
<p>
 <a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or
 <a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>?
</p>
<script>
 var currentPage = 5; // prefilled by server!!!!
 function go(d) {
     setupPage(currentPage + d);
     history.pushState(currentPage, document.title, '?x=' + currentPage);
 }
 onpopstate = function(event) {
     setupPage(event.state);
 }
 function setupPage(page) {
     currentPage = page;
     document.title = 'Line Game - ' + currentPage;
     document.getElementById('coord').textContent = currentPage;
     document.links[0].href = '?x=' + (currentPage+1);
     document.links[0].textContent = 'Advance to ' + (currentPage+1);
     document.links[1].href = '?x=' + (currentPage-1);
     document.links[1].textContent = 'retreat to ' + (currentPage-1);
 }
</script>

这是一个别人写的栗子,我们点击 Advance to ? 对应的 url 与模版都会 +1,反之点击 retreat to ? 就会都 -1,这就满足了 url 与模版视图同时变化的需求 (ง •_•)ง ~~

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值