在 Vue 中离开页面之前如何警告用户未保存的更改

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 吗?我会调查导航守卫。我记住了它们,但我自己还没有使用过它们。这是关于它们的文档:https://router.vuejs.org/guide/advanced/navigation-guards.html

假设您正在使用 vue-router (and you probably should be), then you'll want to use the beforeRouteLeave guard. 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) { ... }

这些答案仅涵盖 Vue 中的导航。如果用户刷新页面或导航到其他站点,则不会被捕获。所以你还需要类似的东西:

window.onbeforeunload = () => (this.unsavedChanges ? true : null);