我有一个Vue组件,它在“脏”(例如未保存)时进行跟踪。如果用户有未保存的数据,我想在他们从当前表单浏览之前警告他们。在典型的web应用程序中,您可以使用onbeforeunload。我曾经尝试过像这样在安装中使用它:
mounted: function(){
window.onbeforeunload = function() {
return self.form_dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
}然而,当使用Vue路由器时,这是不起作用的。它将允许您导航到尽可能多的路由器链接,你想。一旦您试图关闭窗口或导航到一个真正的链接,它将警告您。
是否有方法在Vue应用程序中复制onbeforeunload,用于正常链接和路由器链接?
发布于 2019-06-11 21:03:36
使用beforeRouteLeave 组件内保护和beforeunload事件。
离开保护通常用于防止用户意外离开路由时未保存的编辑。可以通过调用next(false)取消导航。
在组件定义中,执行以下操作:
beforeRouteLeave (to, from, next) {
// If the form is dirty and the user did not confirm leave,
// prevent losing unsaved changes by canceling navigation
if (this.confirmStayInDirtyForm()){
next(false)
} else {
// Navigate to next view
next()
}
},
created() {
window.addEventListener('beforeunload', this.beforeWindowUnload)
},
beforeDestroy() {
window.removeEventListener('beforeunload', this.beforeWindowUnload)
},
methods: {
confirmLeave() {
return window.confirm('Do you really want to leave? you have unsaved changes!')
},
confirmStayInDirtyForm() {
return this.form_dirty && !this.confirmLeave()
},
beforeWindowUnload(e) {
if (this.confirmStayInDirtyForm()) {
// Cancel the event
e.preventDefault()
// Chrome requires returnValue to be set
e.returnValue = ''
}
},
},发布于 2022-01-08 16:45:15
完全模仿这一点的最简单的解决方案如下:
{
methods: {
beforeWindowUnload (e) {
if (this.form_dirty) {
e.preventDefault()
e.returnValue = ''
}
}
},
beforeRouteLeave (to, from, next) {
if (this.form_dirty) {
next(false)
window.location = to.path // this is the trick
} else {
next()
}
},
created () {
window.addEventListener('beforeunload', this.beforeWindowUnload)
},
beforeDestroy () {
window.removeEventListener('beforeunload', this.beforeWindowUnload)
}
}https://stackoverflow.com/questions/56550164
复制相似问题