Blog>
Snippets

Two-Way Data Binding (v-model) With Reactivity

Explain two-way data binding using v-model in Vue 3 and how changes in the UI input immediately affect the reactive data and vice versa.
<template>
  <input v-model="message" placeholder="Edit me">
  <p>The message is: {{ message }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    // Reactive reference
    const message = ref('');

    // Return to the template
    return { message };
  }
};
</script>

<style>
input {
  margin: 10px 0;
}
</style>
This Vue 3 component demonstrates the two-way data binding using v-model. The 'v-model' directive on the input element binds the input's value to the 'message' reactive data property. When the input's value changes, 'message' is updated and vice versa, ensuring that the UI and the data stay in sync.