[英]How do I warn a user of unsaved changes before leaving a page in Vue
我有一个UnsavedChangesModal
作为组件,当用户在输入字段中有未保存的更改(我在页面中有三个输入字段)尝试离开页面时需要启动它。
components: {
UnsavedChangesModal
},
mounted() {
window.onbeforeunload = '';
},
methods: {
alertChanges() {
}
}
假设您正在使用vue-router (您可能应该使用),那么您将需要使用beforeRouteLeave
守卫。 该文档甚至给出了这种确切情况的示例:
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) { ... }
这些答案仅涵盖 Vue 中的导航。 如果用户刷新页面或导航到不同的站点,则不会被捕获。 所以你还需要类似的东西:
window.onbeforeunload = () => (this.unsavedChanges ? true : null);
你在使用 vue-router 吗? 我会研究导航守卫。 我记住了它们,但我自己还没有使用它们。 这是关于它们的文档: https : //router.vuejs.org/guide/advanced/navigation-guards.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.