JAVASCRIPT

Custom Vue 3 v-model for Multiple Properties

Create custom input components in Vue 3 that utilize v-model for multiple properties simultaneously, enabling flexible and powerful two-way data binding.

<!-- CustomMultiInput.vue -->
<template>
  <div>
    <label>Text Input:</label>
    <input
      type="text"
      :value="modelValue" 
      @input="$emit('update:modelValue', $event.target.value)"
      placeholder="Enter text..."
    />
  </div>
  <div>
    <label>Select Option:</label>
    <select
      :value="selectOption" 
      @change="$emit('update:selectOption', $event.target.value)"
    >
      <option value="">-- Select an option --</option>
      <option value="alpha">Alpha</option>
      <option value="beta">Beta</option>
      <option value="gamma">Gamma</option>
    </select>
  </div>
</template>

<script setup>
defineProps({
  modelValue: String, // Default v-model prop
  selectOption: String // Custom v-model prop
});

defineEmits(['update:modelValue', 'update:selectOption']);
</script>

<!-- ParentComponent.vue usage -->
<template>
  <div>
    <h1>Parent Component</h1>
    <CustomMultiInput
      v-model="inputText"
      v-model:selectOption="selectedFilter"
    />
    <p>Text: {{ inputText }}</p>
    <p>Selected Filter: {{ selectedFilter }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import CustomMultiInput from './CustomMultiInput.vue';

const inputText = ref('Initial Text');
const selectedFilter = ref('beta');
</script>
How it works: In Vue 3, `v-model` is syntactic sugar for a `modelValue` prop and an `update:modelValue` event. You can create multiple `v-model` bindings on a single component by defining custom props and their corresponding `update:propName` events. This allows for powerful two-way data binding for complex components that manage several internal values, making the component API cleaner and more intuitive when consumed by parent components.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs