我有一个 UnsavedChangesModal
作为组件,当用户在输入字段中有未保存的更改(我在页面中有三个输入字段)时试图离开页面时需要启动该组件。
components: {
UnsavedChangesModal
},
mounted() {
window.onbeforeunload = '';
},
methods: {
alertChanges() {
}
}
最佳答案
假设您使用的是 vue-router (你可能应该这样做),然后你会想要使用 beforeRouteLeave
守卫。 The documentation甚至给出了这种确切情况的例子:
beforeRouteLeave (to, from , next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false)
}
}
可以直接在您的组件上添加:
components: { ... },
mounted: { ... }
methods: { ... },
beforeRouteLeave (to, from, next) { ... }
关于javascript - 在 Vue 中离开页面之前如何警告用户未保存的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293861/