JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is two-way binding in Vue.js?

Asked on Sep 28, 2024

Answer

Two-way binding in Vue.js allows you to synchronize data between the model and the view, so changes in the UI automatically update the data and vice versa. This is commonly achieved using the "v-model" directive.
<!-- BEGIN COPY / PASTE -->
        <div id="app">
            <input v-model="message" placeholder="Type something">
            <p>The message is: {{ message }}</p>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
        <script>
            new Vue({
                el: '#app',
                data: {
                    message: ''
                }
            });
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "v-model" directive binds the input field to the "message" data property.
  • When you type in the input field, the "message" property updates automatically.
  • Similarly, if the "message" property changes programmatically, the input field reflects the new value.
  • This ensures that the UI and data model are always in sync.
✅ Answered with JavaScript best practices.
← Back to All Questions