All files / src/libs/vee bindV.ts

0% Statements 0/32
100% Branches 1/1
100% Functions 1/1
0% Lines 0/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                                                                                                     
// /src/libs/vee/bindV.ts
import { computed, type Ref } from 'vue'
import { useField } from 'vee-validate'
 
/**
 * Vuetify向けの v-model / error 表示バインド。
 * submitCount>0 または touched/validated のときだけエラーを見せる。
 *
 * opts:
 *  - emptyToNull: true のとき、'' | undefined を null に揃える(クリア時対策)
 *  - toNumber:    true のとき、'123' を 123 に、'' は null(emptyToNull と併用推奨)
 */
export function useVuetifyField<T = any>(
  name: string,
  submitCount: Ref<number>,
  opts?: { emptyToNull?: boolean; toNumber?: boolean }
) {
  const { value, handleChange, handleBlur, errorMessage, meta } = useField<T>(name as any)
 
  const showError = computed(
    () => !!errorMessage.value && (meta.touched || submitCount.value > 0 || meta.validated),
  )
 
  const onUpdate = (raw: any) => {
    let v: any = raw
 
    // 1) クリア時の undefined/'' を null に寄せる
    if (opts?.emptyToNull && (v === '' || v === undefined)) {
      v = null
    }
 
    // 2) 数値に寄せる('1' → 1、' ' → null)
    if (opts?.toNumber && v != null) {
      if (typeof v === 'string') {
        const s = v.trim()
        v = s === '' ? null : Number(s)
      }
    }
 
    handleChange(v as T)
  }
 
  return computed(() => ({
    modelValue: value.value as any,
    'onUpdate:modelValue': onUpdate,
    onBlur: handleBlur,
    error: showError.value,
    'error-messages': showError.value && errorMessage.value ? [String(errorMessage.value)] : [],
  }))
}