当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 关于页面数据未保存改变路由(beforeunload,beforeRouteLeave)

关于页面数据未保存改变路由(beforeunload,beforeRouteLeave)

2019年07月26日  | 移动技术网IT编程  | 我要评论

  一下内容为笔者个人理解,如有出入还请大佬指出不胜感激

  页面有数据未保存,用户离开页面分为两种

    1 . 直接关闭浏览器标签 或者点击浏览器后退按钮 离开当前页面

    2. 在页面内改变路由,或则刷新页面(不包含新标签页打开页面‘target=_blank’)

 

  先说第1种情况 通过关闭页签和后退按钮 

    

   1 通过window的api  beforeunload 
      
window.addeventlistener('beforeunload', (event) => {
  // cancel the event as stated by the standard.
  event.preventdefault();
  // chrome requires returnvalue to be set.
  event.returnvalue = '';
});

    注意 event.preventdefault();谷歌不兼容该方法(详细兼容见下文兼容详图)

  笔者实现如下

    

 addbeforeunloadhandler(){
      window.addeventlistener('beforeunload', this.beforeunloadhandler, false);
    },

 注意这里是callback 该事件对象可以设置提示语(目前官方文档标明不推荐使用兼容性很差具体兼容见下文兼容详图)

 

   通过watch监听是否有数据未保存来判断 注册该方法还是清除该方法 

    清除注册的监听事件

delebeforeunloadhandler(){
      window.removeeventlistener('beforeunload', this.beforeunloadhandler, false);
    }

 自定义提示语的callback,注意兼容问题

    

    事件监听:

  

 

  简单的一段代码可以避免用户误操作丢失数据的蛋疼问题(通常丢失数据的误操作会问候无辜的码农们emmmm)

    兼容详图  地址 https://developer.mozilla.org/en-us/docs/web/api/window/beforeunload_event

    

   

  2 用户在页面中点击链接跳转页面和刷新页面 vue的 beforerouteleave 路由导航 
beforerouteleave(to,form,next){
  let that=this
  if(that.ispreservation){ 
    that.$confirm('有未保存数据,继续该操作数据将丢失。是否确认?', '提示', {
    confirmbuttontext: '确定',
    cancelbuttontext: '取消',
    type: 'warning'
    }).then(()=>{
    next()
    })
  }else{
     next()
  }

 自己的代码段(生命周期函数别大意写到其他生命周期函数内部了)  
 关于 to form next就不用介绍了 一般开发应该都知道是干嘛的。next(false) 取消导航  

 

  该方法为笔者自己项目使用的ui框架,就是弹窗而已,根据自己情况使用

  

  两者一起使用,让用户未保存数据时无路可走。

      

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网