In Vue.js, two-way binding can be achieved using the v-model
directive. v-model
is a convenient directive that allows you to create two-way data bindings on form input elements and custom components.
Here's how you can implement two-way binding using v-model.
<template>
<div>
<!-- Input field with v-model -->
<input type="text" v-model="message">
<!-- Display the message -->
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: '' // Initialize data property
};
}
}
</script>
In this example:
- We have an input field bound to the
message
data property using v-model
.
- Whenever the user types something into the input field, the
message
data property is updated automatically.
- Additionally, any changes to the
message
data property will be reflected in the input field, ensuring two-way binding.
Two-way binding with v-model
Two-way binding with v-model
is not limited to input elements; it can also be used with other form elements like <select>
and <textarea>
. Additionally, you can use v-model
it with custom components by implementing the model
option, allowing you to create custom two-way bindings for your components.
Here's an example of using v-model
a custom component.
<template>
<div>
<!-- Custom component with v-model -->
<custom-input v-model="customMessage"></custom-input>
<!-- Display the custom message -->
<p>{{ customMessage }}</p>
</div>
</template>
<script>
import CustomInput from './CustomInput.vue'; // Import custom component
export default {
components: {
CustomInput // Register custom component
},
data() {
return {
customMessage: '' // Initialize data property
};
}
}
</script>
In this example, assuming CustomInput
is a custom component that supports the v-model
directive, the two-way binding works similarly to the input field example. The customMessage
data property is bound to the custom component, enabling two-way data flow between the parent and child components