Forms guide · 6 of 8
Loading and reacting
Defaults can arrive after the form exists, fields can follow each other, and a form can live outside a component.
Defaults that load later defaultValuesreset
Pass a ref, such as a query’s data. The form is usable while it’s undefined and takes the data when it arrives. Data that arrives after the user has typed doesn’t overwrite the edit. After a save, reset(saved) makes the saved values the new defaults.
Fields that follow others watch
country.watch() runs when a user edit or setValue changes the value. Here it clears the city. It doesn’t run for reset() or loaded defaults, so data that arrives with both a country and a city keeps both. A list of options that depends on a value is a plain computed.
In a dialog reset
Put the form in its own component inside the dialog. vael-ui’s Dialog renders its content only while open, so each open creates a new form, already filled in, with nothing to reset. A form that stays mounted needs reset(record) when the dialog opens.
In a store
A form is a plain object that keeps its reactivity anywhere: a Pinia store, a composable, a prop. The form in onSubmit’s context is the same form. Give a form outside a component an id if you render on the server.
export const useSignup = defineStore('signup', () => {
const form = useForm({
schema,
id: 'signup',
onSubmit: async (values, { form }) => {
try {
await api.signUp(values)
} catch {
form.setErrors({ email: 'That email is already registered' })
}
},
})
return { form }
})Reusable inputs
A field is a typed object, so a reusable input takes it as a prop. form.field('email') gives one field with its value, error and attrs.
<!-- TextField.vue -->
<script setup lang="ts">
import type { Field } from 'vael-form'
defineProps<{ field: Field<string>; label: string }>()
</script>
<template>
<Field :label="label" :error="field.error">
<Input v-model="field.value" v-bind="field.attrs" />
</Field>
</template>
<!-- <TextField :field="form.field('email')" label="Email" /> -->In child components useFormContext
useFormContext() gives a child component the same typed form, for a step or a section in its own file. useField(() => props.name) binds a reusable input by name.
<!-- AccountStep.vue, inside the form's component -->
<script setup lang="ts">
import { useFormContext } from 'vael-form'
import type { schema } from './schema'
const { model, errors, attrs } = useFormContext<typeof schema>()
const { account } = model
</script>