useError.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { AnyJson, AnyStore } from '~/types/interfaces'
  2. import {computed, ComputedRef, useContext} from "@nuxtjs/composition-api";
  3. /**
  4. * @category composables/form
  5. * @class UseError
  6. * Use Classe pour gérer l'apparition de message si le formulaire est dirty
  7. */
  8. export class UseError {
  9. private store: AnyStore
  10. constructor () {
  11. const {store} = useContext()
  12. this.store = store
  13. }
  14. /**
  15. * Composition function
  16. */
  17. public invoke (field: string, emit: any): AnyJson {
  18. const error:ComputedRef<Boolean> = computed(()=>{
  19. return this.store.state.form.violations.indexOf(field) >= 0
  20. })
  21. return {
  22. onChange: (fieldValue:any) => this.onChange(emit, fieldValue, field),
  23. error
  24. }
  25. }
  26. /**
  27. *
  28. */
  29. private onChange (emit:any, fieldValue:any, changeField:string) {
  30. const errors = this.store.state.form.violations.filter((field:string) => field !== changeField)
  31. this.store.commit('form/setViolations', errors)
  32. emit('update', fieldValue, changeField)
  33. }
  34. }
  35. export const $useError = (field: string, emit: any) => new UseError().invoke(field, emit)