Vue Form Inputs

Vue Advanced Form Inputs

We previously learned how v-model perfectly binds simple text fields and checkboxes.

However, modern applications often require complex, custom-built form components like searchable dropdowns or toggle switches.

Vue allows you to use v-model on your very own custom components!


How v-model Works Under the Hood

To make a custom component compatible with v-model, we must understand how it operates.

When you use v-model="searchText", Vue actually expands it into two separate actions:

  1. It binds a prop named modelValue to the component.
  2. It listens for an event named update:modelValue to catch changes.

Creating a Custom Input Component

To build a custom input, your child component must accept the modelValue prop.

Then, when the user types or clicks, it must $emit the update:modelValue event containing the new data.

Custom Input Component:

<!-- ChildComponent.vue -->
<template>
  <input 
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
  />
</template>

<script setup> defineProps(['modelValue']) defineEmits(['update:modelValue']) </script>


Multiple v-models

Sometimes a single custom component needs to bind multiple different values.

For example, a <UserNameInput> might need to bind both a firstName and a lastName.

Vue 3 allows you to target specific prop names by appending a colon: v-model:firstName="first".

Multiple v-model Bindings:

<!-- Parent Component -->
<UserNameInput
  v-model:firstName="first"
  v-model:lastName="last"
/>

This flexibility is why Vue is universally loved for building complex form architectures!


Exercise 1 of 2

?

When you place v-model on a custom component, what is the default prop name Vue passes down?

Exercise 2 of 2

?

What exact event must the custom child component emit to update the v-model value?