useField
A single form field — for your own field components. Gives a value for v-model, the error and ready-made attributes: name (needed to focus errors), id, aria-invalid, aria-describedby — screen readers will read the error text.
Signature
ts
function useField<T>(path: MaybeRefOrGetter<string>): Field<T>
function useField<T>(form: Form, path: MaybeRefOrGetter<string>): Field<T>| Returns | Description |
|---|---|
value | The field value — for v-model |
error | The error text, if it should be shown |
touched, dirty | Whether the user left the field; whether the value differs from the initial one |
attrs | name, id, aria-invalid, aria-describedby, onBlur — for v-bind on <input> |
errorId | id for the element with the error text |
onBlur | Mark the field as touched |
path can be a ref or a getter — the field switches to another path.
Without form the form comes from the context — from useForm or <TvForm> up the component tree.
Example
vue
<!-- TextField.vue -->
<script setup lang="ts">
import { useField } from 'tinyval-vue';
const props = defineProps<{ path: string; label: string }>();
const { value, error, attrs, errorId } = useField<string>(() => props.path); // the form comes from the parent
</script>
<template>
<label :for="attrs.id">{{ label }}</label>
<input v-model="value" v-bind="attrs" />
<span v-if="error" :id="errorId" role="alert">{{ error }}</span>
</template>vue
<form @submit="submit">
<TextField path="name" label="Name" />
<TextField path="email" label="Email" type="email" />
</form>