Skip to content

useFormControl

The useFormControl composable provides the logic and state management for building custom form control components that integrate with the Vue Interface form system.

Usage

typescript
import { useFormControl } from '@vue-interface/form-control';

const { 
    controlAttributes,
    controlClasses,
    formGroupClasses,
    hasChanged,
    hasFocus,
    hasIcon,
    isDirty,
    isEmpty,
    isInvalid,
    isValid,
    listeners,
    model 
} = useFormControl({
    props,
    emit,
    model // Optional custom model ref
});

Arguments

The useFormControl function accepts an options object with the following properties:

PropertyTypeDescription
propsFormControlPropsThe props object from the component.
emitEmitFnThe emit function from the component.
modelModelRef(Optional) A ModelRef for the v-model binding.

Returns

The composable returns an object with the following properties:

PropertyTypeDescription
controlAttributesComputedRef<FormControlAttributes>Attributes to bind to the input element (id, name, class, disabled, readonly, etc.).
controlClassesComputedRef<FormControlClasses>CSS classes for the control element based on state (valid/invalid, focus, size, color, etc.).
formGroupClassesComputedRef<FormGroupClasses>CSS classes for a wrapper/group element (has-activity, has-icon, is-dirty, etc.).
hasChangedRef<boolean>true if the value has been modified from initial state.
hasFocusRef<boolean>true if the control currently has focus.
hasIconComputedRef<boolean>true if an icon slot is present.
isDirtyRef<boolean>true if the value is not null/undefined (set on mount or change).
isEmptyRef<boolean>true if the value is empty.
isInvalidComputedRef<boolean>true if the control is in an invalid state.
isValidComputedRef<boolean>true if the control is in a valid state.
listenersFormControlListenersEvent listeners to bind to the input element (onFocus, onBlur, onInput, etc.).
modelModelRefThe model reference.

Component Implementation

When building a custom form control, spread the controlAttributes and listeners onto your native input element.

vue
<template>
    <div :class="formGroupClasses">
        <label v-if="label" :for="id" :class="labelClass">
            {{ label }}
        </label>
        <div class="relative">
            <input 
                v-bind="controlAttributes" 
                v-on="listeners" 
                :value="model"
            />
            <!-- Slots for icons, activity, etc. -->
        </div>
        <!-- Feedback and errors -->
    </div>
</template>

<script setup lang="ts">
import { useFormControl } from '@vue-interface/form-control';

// ... define props and emits ...

const { 
    controlAttributes, 
    formGroupClasses, 
    listeners, 
    model 
} = useFormControl({ props, emit });
</script>