前端的路由掌握

近来spa很盛行,实在所谓spa就是服务端供应数据,前端js举行衬着转变容器里的内容,新手初探。这里就涉及到路由掌握,现在路由掌握有两种:

路由掌握

1. hash的路由

也就是相似angular和vue现在完成的路由,总会在path背面加上#!这些,个人以为不是很雅观,固然兼容性没得说,ie6也是支撑的。

2. history的路由

history是html5新增加的api,这边不多说了,横竖网上一大堆引见,history的路由上风在于雅观(个人感觉),瑕玷也就是兼容问题了,如图:

《前端的路由掌握》

路由完成

先看个简朴的演示吧
《前端的路由掌握》
能够看到内容是跟着路由的转变而转变的,这里没有用ajax,就是简朴的替代内容,不过意义是一样的。那末代码是怎样的呢

var els=document.querySelectorAll('.el');
//增加事宜
window.addEventListener('click',function(e){
  if(e.target.className==='el'){
    console.log(history.state)
    if(location.pathname.slice('1')===e.target.innerText){
      history.replaceState(null,'el',e.target.innerText)
    }else {
      history.pushState(null,'el',e.target.innerText)
    }

    document.querySelector('#app-container').innerHTML=e.target.innerText
  }
})
//触发回退行进事宜
window.addEventListener('popstate',function(e){
  document.querySelector('#app-container').innerHTML=location.pathname.slice(1)
})

就是这么简朴的一个例子。我也是刚摸清楚,过段时间继承更新。

    原文作者:xiadd
    原文地址: https://segmentfault.com/a/1190000004862711
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞