知道路由的方便之处下面是它两种模式的原理(默认是hash)
hash 通过地址栏进行切换(不利于搜索引擎优化) 首先他利用了浏览器对于hash这种当时不进行刷新,然后通过hashchange监听hash的改变来进行dom的重新渲染,改变组件引进一个新组件
function render(){ let path=location.hash.substring(1);//拿到#后的地址 let component=router.find(value=>value.path===path)['component']; $box.html(component); //这是域名后面的内容 } $(window).on('hashchange',function(){ //来侦测前进后退 单页面的原因是局部组建的渲染 render(); }) $lis.on('click',function(){//对切换的组件们绑定点击事件 let index=$(this).index;//记录路由下标 location.hash=router[index]['path']; }) //bom操作定义路由的时候是数组格式,以此拿到路由的地址 //地址栏会记录hash的操作记录 这是做路由的基本 //location.href=location.origin+'#'+router[index]['path']只有#不会刷新页面,因为这是hash这个与hash原理类似
function render(){//更新dom let path=location.pathname; let component=router.find(value=>value.path===path)['component']; $box.html(component); } $lis.on('click',function(){ let index=$(this).index; history.pushState(null,'',location.origin+router[index]['path']); //第三个参数是路径 pushState有一个缺点 他不会进行页面刷新渲染 所以要手动更新 render(); }) $(window).on('popState',function(){//只能通过前进后退按钮触发,也就是实现前进后退时重新渲染页面 render(); })