vue中使用onbeforeunload

前言:

      onbeforeunload事件可以用在页面刷新前,页面关闭前,进行提示判断等相关操作。也就是说你再这个事件里面添加的操作,你点击f5刷新或者退出这个页面都会触发。

效果图:

js和vue中通过案例来说明用法:

一、js中使用方法:

<html>
	<head>
		<title>this is id onbeforunload  event test</title>
	</head>
	<script type="text/javascript" language="javascript">
		var goodexit=false;
		function bindunbeforunload(){
			goodexit=false;
			window.onbeforeunload=perforresult;
		}
		function unbindunbeforunload(){
			goodexit=true;
			window.onbeforeunload=null;
		}
		function perforresult(){
			if(!goodexit){
				return"当前操作未保存,如果你此时离开,所做操作信息将全部丢失,是否离开?";
			}
		}
	</script>
	<body onload="javascript:return bindunbeforunload();">
		<h1>test is start</h1>
		<input type="button" value="绑定事件" id="btnBind" onclick="return bindunbeforunload();"/>
		<input type="button" value="删除绑定事件"  id="btnUnBind" onclick="unbindunbeforunload();"/>
	</body>
</html>

二:vue中使用:

1、在路由跳转之前来添加事件

 mounted () {
    window.onbeforeunload = function (e) {
      return ''
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.progressVisible) {
      this.$confirm('系统可能不会保存您所做的更改。', '离开此页面?', {
        confirmButtonText: '离开',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        next()
      })
    } else {
      next()
    }
  },
  beforeDestory () {
    window.onbeforeunload = null
  } 

2、直接使用,但是必须有return值

mouted(){
     window.onbeforeunload = () =>{
            this.clearViews();
            return 'tips';
        }
},
methods:{
    clearViews(){
        alert(1);
    }
}

更多文献:

https://www.jianshu.com/p/db0c2125108a

猜你喜欢

转载自blog.csdn.net/qq_41619796/article/details/107936810