useForm.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { AnyJson, AnyStore } from '~/types/interfaces'
  2. import {computed, ComputedRef, useStore} from "@nuxtjs/composition-api";
  3. /**
  4. * @category Use/form
  5. * @class UseDirtyForm
  6. * Use Classe pour gérer l'apparition de message si le formulaire est dirty
  7. */
  8. export class UseForm {
  9. private store: AnyStore
  10. private readonly handler: any
  11. constructor () {
  12. this.store = useStore()
  13. this.handler = getEventHandler()
  14. }
  15. /**
  16. * Composition function
  17. */
  18. public invoke (): AnyJson {
  19. const readonly: ComputedRef<boolean> = computed(() => {
  20. return this.store.state.form.readonly
  21. })
  22. return {
  23. markFormAsDirty: () => this.markAsDirty(),
  24. markFormAsNotDirty: () => this.markAsNotDirty(),
  25. readonly
  26. }
  27. }
  28. /**
  29. * définit le formulaire comme Dirty (modifié)
  30. */
  31. private markAsDirty () {
  32. this.store.commit('form/setDirty', true)
  33. this.addEventListener()
  34. }
  35. /**
  36. * Définit le formulaire comme non dirty (non modifié)
  37. */
  38. private markAsNotDirty () {
  39. this.store.commit('form/setDirty', false)
  40. this.clearEventListener()
  41. }
  42. /**
  43. * Ajoute un Event avant le départ de la page
  44. */
  45. private addEventListener () {
  46. if (process.browser) {
  47. window.addEventListener('beforeunload', this.handler)
  48. }
  49. }
  50. /**
  51. * Supprime l'Event avant le départ de la page
  52. */
  53. private clearEventListener () {
  54. if (process.browser) {
  55. window.removeEventListener('beforeunload', this.handler)
  56. }
  57. }
  58. }
  59. function getEventHandler () {
  60. return function (e: any) {
  61. // Cancel the event
  62. e.preventDefault()
  63. // Chrome requires returnValue to be set
  64. e.returnValue = ''
  65. }
  66. }
  67. export const $useForm = () => new UseForm().invoke()