useForm.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { AnyStore } from '~/types/interfaces'
  2. import {computed, ComputedRef} from "@nuxtjs/composition-api";
  3. /**
  4. * @category composables/form
  5. * @param store
  6. * Composable pour gérer l'apparition de message si le formulaire est dirty
  7. */
  8. export function useForm(store: AnyStore){
  9. const handler: any = getEventHandler()
  10. const readonly: ComputedRef<boolean> = computed(() => {
  11. return store.state.form.readonly
  12. })
  13. /**
  14. * définit le formulaire comme Dirty (modifié)
  15. */
  16. function markAsDirty () {
  17. store.commit('form/setDirty', true)
  18. if (process.browser) {
  19. window.addEventListener('beforeunload', handler)
  20. }
  21. }
  22. /**
  23. * Définit le formulaire comme non dirty (non modifié)
  24. */
  25. function markAsNotDirty () {
  26. store.commit('form/setDirty', false)
  27. if (process.browser) {
  28. window.removeEventListener('beforeunload', handler)
  29. }
  30. }
  31. return {
  32. markAsDirty,
  33. markAsNotDirty,
  34. readonly
  35. }
  36. }
  37. function getEventHandler () {
  38. return function (e: any) {
  39. // Cancel the event
  40. e.preventDefault()
  41. // Chrome requires returnValue to be set
  42. e.returnValue = ''
  43. }
  44. }