Vue监听浏览器刷新和关闭事件
在前端开发中,我们通常会遇到这样的需求,用户离开、刷新页面前,修改数据未进行保存操作,需要提示框提醒用户
效果实现
methods: {/** 在刷新和关闭之前询问 **/beforeRefreshClose() {let self = this;window.onbeforeunload = function (e) {if (self.$route.name == "路由名称") {e = e || window.event;// 兼容IE8和Firefox 4之前的版本if (e) e.returnValue = "关闭提示1";// Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+return "关闭提示2";} else window.onbeforeunload = null;};},
},
mounted() {this.beforeRefreshClose();
}