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

dub*_*ons 11 javascript vue.js vue-router vuejs2

我有一个 Vue 组件,它在“脏”(例如未保存)时进行跟踪。如果用户有未保存的数据,我想在他们浏览当前表单之前警告用户。在典型的 Web 应用程序中,您可以使用onbeforeunload. 我试图在这样的安装中使用它:

mounted: function(){
  window.onbeforeunload = function() {
    return self.form_dirty ? "If you leave this page you will lose your unsaved changes." : null;
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,这在使用 Vue Router 时不起作用。它可以让您根据需要导航尽可能多的路由器链接。只要您尝试关闭窗口或导航到真实链接,它就会警告您。

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

Ric*_*cky 20

beforeRouteLeave 组件内防护beforeunload事件一起使用。

离开守卫通常用于防止用户因未保存的编辑而意外离开路线。可以通过调用 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 = ''
    }   
  },
},
Run Code Online (Sandbox Code Playgroud)