Vue.js 2 アプリケーションで onbeforeunload を模倣するにはどうすればよいですか? 質問する

Vue.js 2 アプリケーションで onbeforeunload を模倣するにはどうすればよいですか? 質問する

私は、"ダーティ" (未保存など) であるかどうかを追跡する 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を使用する場合には機能しません。ルーターリンクを好きなだけ移動することができます。ウィンドウを閉じたり、本物リンクをクリックすると警告が表示されます。

onbeforeunloadVue アプリケーションで通常のリンクとルーター リンクを複製する方法はありますか?

ベストアンサー1

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

おすすめ記事