Skip to content

Function: useLocalizedModelValue()

ts
function useLocalizedModelValue<ComponentProps, ModelValueProp, Inner>(
  props: ComponentProps,
  prop: ModelValueProp,
  defaultvalue?: ComponentProps[ModelValueProp],
  transformIn?: (value?: ComponentProps[ModelValueProp]) => Inner,
  transformOut?: (value: Inner) => ComponentProps[ModelValueProp],
  onUpdate?: (value: ComponentProps[ModelValueProp]) => void,
): WritableComputedRef<Inner, Inner>;

Composable for managing localized/transformed model values with bidirectional synchronization.

This composable creates a local ref that syncs with a parent prop, allowing you to transform values as they flow in and out (e.g., for encoding/decoding, formatting). It uses shallow refs and encoded comparison to detect meaningful changes and avoid unnecessary updates.

Type Parameters

Type ParameterDefault typeDescription
ComponentProps extends { [key in string as `onUpdate:${ModelValueProp}`]: ((args: any[]) => void) | undefined }-The component props type, must have an onUpdate:${ModelValueProp} event handler
ModelValueProp extends string-The name of the model value prop (e.g., 'modelValue')
InnerComponentProps[ModelValueProp]The transformed/internal type of the value (defaults to the prop's type)

Parameters

ParameterTypeDescription
propsComponentPropsThe component props object
propModelValuePropThe name of the model value prop to bind to
defaultvalue?ComponentProps[ModelValueProp]Optional default value when the prop is undefined
transformIn?(value?: ComponentProps[ModelValueProp]) => InnerFunction to transform incoming prop values to internal representation. Default is identity.
transformOut?(value: Inner) => ComponentProps[ModelValueProp]Function to transform internal values back to prop values. Default is identity.
onUpdate?(value: ComponentProps[ModelValueProp]) => voidCallback invoked when the internal value changes and needs to be committed to the parent

Returns

WritableComputedRef<Inner, Inner>

A computed ref that provides a two-way binding with get/set semantics

Remarks

  • Uses shallowRef for performance with potentially large or complex transformed values
  • Employs encode() for deep comparison to detect actual changes, avoiding redundant updates
  • Calls triggerRef() to ensure shallow ref changes propagate when needed
  • The setter emits changes via the onUpdate callback (normally bound to the parent's onUpdate handler)
  • Watch on parent prop changes automatically updates the local state via transformIn

Example

typescript
// For a field that encodes/decodes internal state
const modelValue = useLocalizedModelValue(
  props,
  "modelValue",
  undefined,
  (val) => decode(val), // decode on input
  (val) => encode(val), // encode on output
  (val) => emit("update:modelValue", val), // emit changes
);