vue 的路由模式

  vue 有两种路由模式,hash和history,
  实现原理:
  1.hash 利用浏览器onhashchang事件,每次hash的值的改变之后url都能被浏览器记录下来,只能修改#后面的参数,从而发现浏览器的前进后退都可以用,只能前进后退一步,url上会带有#;
  2.history 利用history api的pushstate和replacestate,给了前端很大的自由;包括 back,forward,go三个方法,对应浏览器的前进,后退,跳转操作。很多小伙伴只知道浏览器有前进和后退,其实在前进后退上长按鼠标,会弹出历史记录,从而完成跳转.
  通过pushstate把页面的状态保存在state对象中,当页面的url再变回这个url时,可以通过event.state取到这个state对象,从而可以对页面状态进行还原,这里的页面状态就是页面字体颜色,其实滚动条的位置,阅读进度,组件的开关的这些页面状态都可以存储到state的里面;
  路由改变会刷新页面,会出现404,要事先准备一个页面跳转,需要后端配置
  代码:
  window.onhashchange = function(event){
      console.log(event.oldURL, event.newURL);
      let hash = location.hash.slice(1);
      document.body.style.color = hash;
  }
  参考链接:https://www.jianshu.com/p/f7326622d49e
           https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90
window.history.pushState({color:'red'}, 'red', '');

 window.onpopstate = function(event){
     console.log(event.state);
     if(event.state && event.state.color === 'red'){
         document.body.style.color = 'red';
     }
 }
posted @ 2020-11-01 12:13  Redbreans  阅读(45)  评论(0)    收藏  举报