Skip to content

useField ​

单个表单字段 —— 用于自定义字段组件。提供 v-model 的值、错误以及现成的属性:name(聚焦错误时需要)、id、aria-invalid、aria-describedby —— 屏幕阅读器会读出错误文本。

签名 ​

ts
function useField<T>(path: MaybeRefOrGetter<string>): Field<T>
function useField<T>(form: Form, path: MaybeRefOrGetter<string>): Field<T>
返回值说明
value字段值 —— 用于 v-model
error应显示时的错误文本
touched、dirty用户是否离开过该字段;值是否与初始值不同
attrsname、id、aria-invalid、aria-describedby、onBlur —— 用于 <input> 上的 v-bind
errorId错误文本元素的 id
onBlur将字段标记为已访问

path 可以是 ref 或 getter —— 字段会切换到另一个路径。

不传 form 时,会从上下文获取表单 —— 来自组件树上层的 useForm 或 <TvForm>。

示例 ​

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>

另请参阅 ​