gpt4 book ai didi

javascript - 如何在 Vue.js 2 应用程序中模拟 onbeforeunload?

转载 作者:行者123 更新时间:2023-12-01 15:38:36 24 4
gpt4 key购买 nike

我有一个 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 Router 时不起作用。它可以让您浏览任意数量的路由器链接。一旦您尝试关闭窗口或导航到真实链接,它就会警告您。

有没有办法复制 onbeforeunload在普通链接和路由器链接的 Vue 应用程序中?

最佳答案

使用 beforeRouteLeave in-component guard连同 beforeunload 事件。

The leave guard is usually used to prevent the user from accidentallyleaving the route with unsaved edits. The navigation can be canceledby calling 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 = ''
}
},
},

关于javascript - 如何在 Vue.js 2 应用程序中模拟 onbeforeunload?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56550164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com