hash和history模式的区别

2021-03-05  本文已影响0人  浅浅_2d5a

hash模式

1、带#号
http://10.46.134.159:8080/#/about
2、能监听hash变化的事件,onhashchange

在hash模式下,通过router-link的to属性和this.$router.push均不会触发onhashchange事件
与之对应的replace也不会触发
执行window.history.back()
window.history.forward()
window.history.go(1)会触发
点击浏览器左上角的前进后退可以触发onhashchange

window.addEventListener(
  'hashchange',
  function (event) {
      const oldURL = event.oldURL; // 上一个URL
      const newURL = event.newURL; // 当前的URL
      console.log(newURL, oldURL);
  },
  false
);

注意:监听方法的调用,要在mounted中,不能在created中
3、兼容性 ie8
4、页面随便刷新

history模式

1、网址正常
http://10.46.134.159:8080/about
2、能监听history变化的事件,onpopstate

在history模式下,
通过router-link的to属性和this.$router.push均不会触发onpopstate事件
调用window.history.pushState 和 window.history.replaceState 不会触发 onpopstate 事件
与之对应的replace也不会触发
执行window.history.back()
window.history.forward()
window.history.go(1)会触发 0是刷新 可传-1
点击浏览器左上角的前进后退可以触发onpopstate
a 标签的锚点也会触发该事件

window.addEventListener("popstate", function() {
    var currentState = history.state;
    console.log('history',history)                                         
});

2个api能控制历史记录栈
(1) window.history.pushState(state, title, url);在浏览器中新增一条历史记录。state是对象,会在onpopstate事件触发时作为参数传递过去,title为页面标题,url为页面地址;
浏览器在调用pushState()方法后不会去加载这个URL,新的URL不一定要是绝对地址,如果它是相对的,它一定是相对于当前的URL。
url不能跨域,否则报错
(2) window.history.replaceState(state, title, url);在浏览器中替换当前历史记录
上述2个api使用场景,控制安卓系统的回退按钮的跳转

history的其他api
history.length():当前历史列表中的历史记录条数;

需要注意:
谷歌浏览器和火狐浏览器在页面第一次打开的反应是不同的,谷歌浏览器奇怪的是会触发 onpopstate 事件,而火狐浏览器则不会
解决:先加入一条记录,在定时器中加onpopstate 的监听
组件释放的时候要记得去掉监听

3、兼容性 ie10
专业网址:
https://developer.mozilla.org/en-US/docs/Web/API/History
onpopstate、pushState、replaceState都是兼容到ie10

image.png

pushState 和 replaceState 两个方法跟 location.href 和 location.replace 两个方法有什么区别呢?应用的场景有哪些呢?

location.href 和 location.replace 切换时要向服务器发送请求,而 pushState 和 replace 仅修改 url

window.location.replace="http://10.46.134.159:8080/about";
location.replace("http://10.46.134.159:8080/about")

image.png

window.location.replace会增加一条history历史记录

另外有history封装的js
https://cdn.bootcss.com/history/4.7.2/history.js

===至于 history刷新404 不懂===

上一篇 下一篇

猜你喜欢

热点阅读