簡體   English   中英

如何在 Vue.js 2 應用程序中模擬 onbeforeunload?

[英]How can I mimic onbeforeunload in a Vue.js 2 application?

我有一個 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 時不起作用。 它可以讓您瀏覽任意數量的路由器鏈接。 一旦您嘗試關閉窗口或導航到真實鏈接,它就會警告您。

有沒有辦法在 Vue 應用程序中為普通鏈接和路由器鏈接復制onbeforeunload

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 = ''
    }   
  },
},

完全模仿這一點的最簡單的解決方案如下:

{
  methods: {
    beforeWindowUnload (e) {
      if (this.form_dirty) {
        e.preventDefault()
        e.returnValue = ''
      }
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.form_dirty) {
      next(false)
      window.location = to.path // this is the trick
    } else {
      next()
    }
  },
  created () {
    window.addEventListener('beforeunload', this.beforeWindowUnload)
  },
  beforeDestroy () {
    window.removeEventListener('beforeunload', this.beforeWindowUnload)
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM