Vue's core features include declarative directives and two-way data binding. After covering declarative directives, we'll examine what constitutes two-way data binding.
Vue follows the MVVM design pattern:
- M represents Model
- V represents View
- VM represents ViewModel
Understanding One-Way vs Two-Way Binding
One-way binding connects Model to View. When JavaScript updates the Model, the View automatically refreshes. Two-way binding adds the reverse capability - when users modify the View (like filling forms), the Model updates automatically.
The relationship can be conceptualized as: Two-way data binding = One-way data binding + UI event monitoring.
Here's a basic example of two-way binding in Vue:
<body>
<div id="container">
<input type="text" v-model="message">
<p>{{message}}</p>
</div>
<script>
var container = new Vue({
el: '#container',
data: {
message: ''
}
})
</script>
</body>
When typing in the input field, the paragraph element synchronously displays the content - demonstrating classic two-way binding. Vue implements this using the v-model directive.
Implementation Behind v-model
According to official documentation, v-model combines v-bind:value and v-on:input.
Consider this example showing computed property getters:
<!-- <input type="text" v-model="userData"> -->
<!-- Equivalent to: -->
<input type="text" v-bind:value="userData" @input="handleInput">
<button @click="submitData">Submit</button>
<div class="output" ref="display"></div>
var formApp = new Vue({
el: '#formContainer',
data: {
userInput: '',
inputValue: ''
},
methods: {
submitData() {
this.$refs.display.innerHTML = this.userData;
},
handleInput(event) {
this.userData = event.target.value;
}
},
computed: {
userData: {
get() {
return this.userInput;
},
set(newVal) {
this.userInput = newVal;
}
}
}
})
This demonstrates how v-model aciheves two-way binding and utilizes computed property setters.
Basic v-model Usage
The v-model directive creates two-way binding on form <input> and <textarea> elements. It automatically selects appropriate update methods based on control type. While appearing magical, v-model is essentially syntactic sugar that listens for input events to udpate data while handling special cases.
Important: v-model works exclusively with form controls including text inputs, multi-line text areas, checkboxes, radio buttons, select dropdowns, and multi-select options.
For comprehensive coverage of all form types and advanced usage patterns, consult the official Vue documentation at https://cn.vuejs.org/v2/guide/forms.html
The official Vue documentation provides excellent resources for understanding form handling capabilities.