programing

Vue.js 2 어플리케이션에서 onbeforeunload를 모방하려면 어떻게 해야 합니까?

bestcode 2022. 8. 30. 22:19
반응형

Vue.js 2 어플리케이션에서 onbeforeunload를 모방하려면 어떻게 해야 합니까?

Vue 컴포넌트가 "더러움"을 추적하고 있습니다(예: 저장되지 않음).저장되지 않은 데이터가 있는 경우 현재 양식을 찾아보기 전에 사용자에게 경고합니다.일반적인 웹 어플리케이션에서는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 어플리케이션에서 라우터 링크뿐만 아니라 일반 링크도 사용할 수 있습니까?

를 사용합니다.beforeRouteLeave 이벤트와 함께 컴포넌트 내 가드.

Leave Guard는 보통 사용자가 실수로 저장되지 않은 편집으로 루트를 이탈하지 않도록 하기 위해 사용됩니다.네비게이션은 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)
  }
}

언급URL : https://stackoverflow.com/questions/56550164/how-can-i-mimic-onbeforeunload-in-a-vue-js-2-application

반응형