Vue Tip: Use Multiple v-model Bindings
The v-model gives the flexibility to use multiple v-model directives on a single component instance.
It is possible to rename modelValue
to whatever we want, and therefore we can use multiple v-model
directives.
Let's take a look at an exemplary App.vue
component that uses HelloWorld
component, which provides two v-model
directives:
1<template>
2 <HelloWorld v-model:firstName="firstName" v-model:lastName="lastName" />
3</template>
4
5<script setup lang="ts">
6import HelloWorld from './components/HelloWorld.vue'
7
8interface Props {
9 firstName: string
10 lastName: string
11}
12
13const props = withDefaults(defineProps<Props>(), {
14 firstName: 'Michael',
15 lastName: 'Hoffmann',
16})
17</script>
And here is the code for HelloWorld.vue
:
1<template>
2 <div class="container">
3 <label>First Name:</label>
4 <input :value="firstName" />
5 <label>Last Name:</label>
6 <input :value="lastName" />
7 </div>
8</template>
9
10<script setup>
11const props = defineProps({
12 firstName: String,
13 lastName: String,
14})
15
16const emit = defineEmits(['update:firstName', 'update:lastName'])
17</script>
The source code for this demo is available at StackBlitz:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Avoid Unwanted Re-Renders of an Element Using v-once
The v-once directive is a Vue.js directive used to avoid unwanted re-renders of an element.
Vue Tip: Trigger Watcher Immediately
The watch hook provides an option that the callback is called immediately.