页面跳转与浏览器记录

location.href = urllocation.reload()location.replace(url)
url完全不变的情况下刷新Docment,不会产生记录刷新Docment,不会产生记录刷新Docment,不会产生记录
只改变hash不会刷新Docment,会在浏览器产生记录,但是如果连续改变hash,也会丢失记录 是不刷新Docment 也不产生记录
改变url,只hash不算,hash从有到无算刷新Document,会产生记录,但是如果页面加载时执行不会产生记录,setTimeout里面执行就会有记录刷新Document,不会产生记录

问题1:

在页面加载的时候直接location.href 到其他的页面,会在浏览器里不留下当前页面的记录,
试验用 setTimeout 0秒后再location.href 到其他的页面则会留下记录。
所以再做页面跳转的时候如果不想留下记录,还是用replace比较保险,如果想留下记录,应该setTimeout几百毫秒再跳转。

问题2:

通过浏览器的前进和后退到页面,页面的Document会从缓存中取,js重新执行。所以如果页面的数据是从模板中下发的,
会导致回退回来的时候页面的模板数据不会刷新。
解决方案


var url = window.location.href;  
var ps = url.split("#");  
    try{  
        if(ps[1] != 1){  
            url += "#1";  
        }else{  
         //当访问页面的时候是有hash =1 证明是从别的url中过来的,所以replace成没有hash的url(这里就会刷新Document)
          window.location.replace(ps[0]);  
          return;
        }  
    }catch(ex){  
        url += "#1";  
    }       
   //页面第一次进来的时候,没有hash = 1,用replace加上hash,这样在跳转到其他页面再返回来的时候是带着hash
    window.location.replace(url);

问题3:

页面中当连续改变hash的时候,也会导致浏览器的历史记录会有丢失,所以快速切换hash也有问题。
但是有的需求是当进入页面的时候需要立刻变成hash2,然后可以点击返回到hash1,
如果从页面中直接从hash1变成hash2会发现hash1的记录消失。
解决办法 先用history.pushState 给浏览器添加一条记录,然后用replace (hash2)的方法替换掉添加的记录,这样记录里存的就是hash1和hash2
解决方案


history.pushState({},document.title, '#/order')
this.$router.replace({
      name: 'Edit'
})

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