Javascript 如何在Vue.js 2应用程序中模拟onbeforeunload?
我有一个Vue组件,它在“脏”时进行跟踪(例如,未保存)。如果用户有未保存的数据,我想在他们离开当前表单浏览之前警告用户。在典型的web应用程序中,您可以使用Javascript 如何在Vue.js 2应用程序中模拟onbeforeunload?,javascript,vue.js,vuejs2,vue-router,Javascript,Vue.js,Vuejs2,Vue Router,我有一个Vue组件,它在“脏”时进行跟踪(例如,未保存)。如果用户有未保存的数据,我想在他们离开当前表单浏览之前警告用户。在典型的web应用程序中,您可以使用onbeforeuload。我曾尝试在安装中使用它,如下所示: mounted: function(){ window.onbeforeunload = function() { return self.form_dirty ? "If you leave this page you will lose your unsaved
onbeforeuload
。我曾尝试在安装中使用它,如下所示:
mounted: function(){
window.onbeforeunload = function() {
return self.form_dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
}
但是,当使用Vue路由器时,这不起作用。它将让你导航下尽可能多的路由器链接,你想。一旦你试图关闭窗口或导航到一个真正的链接,它就会警告你
是否有方法在Vue应用程序中为正常链路和路由器链路复制
onbeforeunload
左侧防护装置通常用于防止用户意外受伤
使用未保存的编辑保留路线。导航可以取消
通过调用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 = ''
}
},
},
在组件上。@tao afaik您不能通过返回false或like@phil294,不,你不能。这没有任何意义。想想看:您有一堆列表元素(Vue组件),在某些数据数组中,每个元素对应一个列表元素。然后更新数组。您的某些元素已从数据中消失。现在,你真的想让你的组件去:“……事实上,我想我会在DOM中停留一段时间。我抗议,我不会被摧毁,好吗?让我打电话给我的律师!还是它是图层?”我认为这不符合确认像OnForeUnload一样关闭窗口的要求。。。有什么方法可以合并吗?@dubloons我误读了你的问题,请使用组件中的
保护来处理路线更改,并在用户尝试关闭窗口时使用beforeuload
事件。