【Vue】指定页面在关闭或刷新浏览器之前出现提示弹框onbeforeunload、离开当前路由页面去到别的路由页面beforeRouteLeave
浏览器自带的onbeforeunload事件可以用在页面刷新前,页面关闭前,进行提示判断等相关操作。离开当前路由页面去到别的路由页面可以使用beforeRouteLeave。比如表单是一个页面,当用户离开的时候,可以进行提示判断是否需要保存,这时就可以用到这个啦。
·
目录
onbeforeunload
浏览器自带的onbeforeunload事件可以用在页面刷新前,页面关闭前,进行提示判断等相关操作。也就是说当你在点击f5刷新、点击刷新按钮或者关闭这个页面都会触发这个事件。
这里我做了一个判断,当我的路由的name是Tree的时候才会在离开页面的时候触发这个事件,其余页面均不会触发这个事件。
写在APP.vue或者所需页面中都可
mounted () {
var that = this
window.onbeforeunload = function (e) {
if (that.$route.name === 'Tree') {
var message = 'some word';
e = e || window.event;
if (e) {
e.returnValue = message;
}
return "浏览器关闭!";
} else {
window.onbeforeunload = null;
}
}
},
beforeDestory () {
window.onbeforeunload = null
},
注意:
1、上面的方法生效的前题是,打开该网页后,需要鼠标点击一下网页,让网页获取焦点,然后再关闭或刷新! 若打开后不点击页面直接关闭或刷新不会触发该方法。
2、必须写return
beforeRouteLeave
beforeRouteLeave(to,from,next)表示离开路由之前执行的函数,可用于页面的反向传值,页面跳转。
<template>
<div>表单</div>
</template>
<script>
export default {
beforeRouteLeave (to, from, next) {
//跳转路由前进行一些操作
。。。。
this.$confirm('有未保存的数据,是否保存数据?', '提示', {
confirmButtonText: '保存',
cancelButtonText: '不保存',
type: 'warning'
}).then(data => {
console.log('保存的操作');
}).catch(err => {
console.log('不保存的操作');
next()//放行
})
}
}
</script>
注意:当页面有返回按钮时,不要用this.$router.go(-1),不然会出现confirm闪出来一下又消失掉
更多推荐
所有评论(0)