Two Way Binding in Vue3

A simple two way binding example in vue3.

Child.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script lang="ts" setup>
const name = defineModel<string>('name');
const age = defineModel<number>('age');

const updateAgeInChild = () => {
++age.value;
};
</script>

<template>
<h1>Child: </h1>
<p>name: {{ name }}</p>
<p>age: {{ age }}</p>
<input type="text" v-model="name"/>
<button @click="updateAgeInChild()">Add age in Child</button>
</template>

Parent.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script lang="ts" setup>
import { ref } from 'vue';
import Child from './Child.vue';

const name = ref('BlockLune');
const age = ref(0);

const updateAgeInParent = () => {
++age.value;
};
</script>

<template>
<Child v-model:name="name" v-model:age="age" />
<h1>Parent: </h1>
<p>name: {{ name }}</p>
<p>age: {{ age }}</p>
<input type="text" v-model="name"/>
<button @click="updateAgeInParent">Add in Parent</button>
</template>

App.vue:

1
2
3
4
5
6
7
<script setup>
import Parent from './Parent.vue';
</script>

<template>
<Parent />
</template>

Learn more at Component v-model | Vue.js. Note the Under the Hood part.