Mokkapps Logo

Vue Tip: Use Multiple v-model Bindings

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
November 25, 2021
1 Minuten Lesezeit
|
- Ansichten

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:

// App.vue

<template>
  <HelloWorld v-model:firstName="firstName" v-model:lastName="lastName" /></template>

<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue';

interface Props {
  firstName: string;
  lastName: string;
}

const props = withDefaults(defineProps<Props>(), {
  firstName: 'Michael',
  lastName: 'Hoffmann',
});
</script>

And here is the code for HelloWorld.vue:

// HelloWorld.vue

<template>
  <div class="container">
    <label>First Name:</label>
    <input :value="firstName" />
    <label>Last Name:</label>
    <input :value="lastName" />
  </div>
</template>

<script setup>
const props = defineProps({
  firstName: String,  lastName: String,});

const emit = defineEmits(['update:firstName', 'update:lastName']);</script>

The source code for this demo is available at StackBlitz:




If you liked this tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github