需求:首先,因为在这个页面用户修改了数据,跳转页面或者重新刷新时要提示下用户是否需要保存
- beforeRouteLeave() 路由组件
Vue Router
提供了一个叫路由组件守卫的东东
这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过
next(false)
来取消。
beforeRouteLeave(to, from, next) {
this.$confirm('返回将丢失此页面数据, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(() => {
next()
})
.catch(() => {
next(false)
})
}
但是,这个只能在跳转路由的时候生效???,所以重载页面的时候是不OK滴
- window.onbeforeunload() 重载页面我们可以用到浏览器自带的
API
来做
当窗口即将被卸载(关闭)时,会触发该事件.此时页面文档依然可见,且该事件的默认动作可以被取消.
mounted() {
console.log(this.mywindow)
this.mywindow.onbeforeunload = function (e) {
e = e || window.event;
// 兼容IE8和Firefox 4之前的版本
if (e) {
e.preventDefault();
e.returnValue = '关闭提示'
}
// Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
return '关闭提示'
}
},
destroyed() {
this.mywindow.onbeforeunload = null
},
到这里我们的需求就完成了???