useForm
Overview
Generate and provide a form context for a form, using the provided initial values, including methods to update the form's values, errors, messages, touched state, modified state, and to reset the form.
Signature
useForm(props)
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| props | object | yes | The form context's initial values. |
props Properties
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| initialValues | object | The form's initial values. Not mutated, but changes reset the form. |
Returns
Examples
vue
<script setup>
import Button from "@vueda/controls/button/Button.vue"
import { ConfirmationRequiredError, ServerFeedbackError } from "@vueda/utils/errors.js";
const myState = reactive({
submitting: false,
// when initialValues is changed, the form's values are reset to match
initialValues: {},
});
const formContext = useForm(myState);
const handleSubmit = async () => {
try {
myState.submitting = true;
// allow all validation to run
formContext.setAllTouched();
await nextTick();
if (formContext.state.anyError) {
return;
}
if (!formContext.state.anyModified) {
return;
}
await submitToServer(formContext.state.submittingValues);
} catch (e) {
if (e instanceof ServerFeedbackError && !(e instanceof ConfirmationRequiredError)) {
formContext.handleServerFormValidationError(e);
return;
}
throw e;
} finally {
myState.submitting = false;
}
};
</script>
<template>
<form @submit.prevent="handleSubmit">
<form-message type="error" />
<form-message type="message" />
<form-field name="field1" label="Field 1">
<form-label>
<widget-input />
</form-label>
</form-field>
<form-field name="field2" label="Field 2" validation="numeric" :max-value="100" :min-value="1">
<form-label>
<widget-input step="1" />
</form-label>
</form-field>
<Button type="submit">Submit</Button>
</form>
</template>Source
client/lib/use/useForm.js:660