自学内容网 自学内容网

vue 判断页面是否刷新-技巧

前端实现

方法一
  1. 在 App.vue 文件中缓存下刷新时当前页面的路由
created() {
    this.currentPathLoad();
},
methods: {
currentPathLoad() {
window.addEventListener("current-path-load",()=>{
      let path = this.$route.path;
      sessionStorage.setItem('current-path-load',JSON.stringify(path));
    })
    }
}
  1. 具体页面实现
methods: {
someMethods() {
// 写对应逻辑 begin
let pagePath = this.$route.path
      let path = JSON.parse(sessionStorage.getItem('current-path-load'))
      if (pagePath === path) {
        console.log('刷新')
        // 如果是刷新,移除缓存的路由,以免造成对其他页面的路由影响
        sessionStorage.removeItem('current-path-load') 
      } else {
        console.log('不是刷新')
   }
// 写对应逻辑 end
    }
}
方法二
mounted(){
if(window.name == ""){
           console.log("首次被加载");
      // 在首次进入页面时我们给window.name设置一个固定值(isRefresh) 
           window.name = "isRefresh"; 
       }else if(window.name == "isRefresh"){
           console.log("页面被刷新");
       }
}
方法三
mounted(){
  if (window.performance.navigation.type == 1) {
        console.log("页面被刷新")
          }else{
        console.log("首次被加载")
          }
}

原文地址:https://blog.csdn.net/weixin_44835297/article/details/142884531

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!