How to use Multiple v-model in a component | VUE 3

Al Emran
2 min readMay 18, 2023

--

Vue 3 multiple v-model

You may already know how to use v-modelon a component. However, in Vue 3, you have the ability to use multiple v-model directives. If you're not familiar with it, allow me to briefly and simply explain it.

To do that bind a value prop and use computed to emitupdate:modelValue custom event.

<!-- EditableTitle.vue -->
<script setup>
import { computed } from 'vue'

const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

const value = computed({
get() {
return props.modelValue
},
set(value) {
emit('update:modelValue', value)
}
})
</script>

<template>
<input v-model="value" />
</template>

Now you can use v-model on EditableTitle.Vue component

<script setup>
import { ref } from "vue"
import EditableTitle from "../components/EditableTitle.vue";

const item = ref({title: 'Some Title', value: 20})
</script>

<template>
<EditableTitle v-model="item.title"/>
</template>

You see on the above code snippet item is an object, what if you what to use multiple v-model one for title and one for value in EditableTitle.Vue component.

Now it’s possible on vue 3 . By default v-model uses modelValue as props. That’s why on the EditableTitle.vue component we received the props as modelValue and emit an event called update:modelValue .

But you can send custom props with v-model . Using this flexibility we will modify EditableTitle.vue to make a new one. We will name it Expense.vue

<script setup>
defineProps({
title: String,
value: Number
})
defineEmits(['update:title', 'update:value'])
</script>
<template>
<input
type="text"
:value="title"
@input="$emit('update:title', $event.target.value)"
>
<input
type="number"
:value="value"
@input="$emit('update:value', $event.target.value)"
>
</template>

Now you can use multiple v-model

<script setup>
...
const item = ref({title: 'Tea', value: 20})
...
</script>
<template>
...

<Expense
v-model:title="item.title"
v-model:value="item.value"
/>
</template>

Hope this post provides a concise guide on leveraging this feature to enhance data interactivity and simplify development in Vue 3.

--

--

Al Emran

" Hello, I'm a programming enthusiast and lifelong learner. Join me as I share what I'm learning and make coding accessible and enjoyable for everyone."