v-model
v-model is a Vue directive used to establish two-way data binding between form input elements and application state. This means that when you input text into an input field, the bound data updates automatically; conversely, when the bound data is modified, the input field content also updates automatically.
Usage: Primarily used for form controls such as <input>, <select>, and <textarea>.
Example:
html<template> <input v-model="message" placeholder="Enter some text"> <p>The entered message is: {{ message }}</p> </template> <script> export default { data() { return { message: '' }; } }; </script>
In this example, v-model binds the input's value to the message property in the data. When the user types into the input field, the message value updates; similarly, if message is changed via other means, the input field displays the latest content.
v-bind
v-bind is a Vue directive used for one-way binding of parent component data to child component properties. It is commonly employed to dynamically set HTML element attributes or child component props.
Usage: Used for handling one-way binding of any HTML attributes or component props.
Example:
html<template> <div> <img v-bind:src="imageSrc" /> </div> </template> <script> export default { data() { return { imageSrc: 'path/to/image.jpg' }; } }; </script>
In this example, v-bind binds the src attribute of the <img> tag to the imageSrc property in the Vue instance's data. When imageSrc changes, the src attribute updates automatically to reflect this change. However, this binding is one-way, meaning modifications to the <img> tag do not affect the imageSrc value.
Summary of Differences
- Data Flow:
v-modelenables two-way binding, whilev-bindsupports one-way binding. - Usage:
v-modelis mainly for form elements, whereasv-bindis used for binding HTML attributes and component props. - Syntax Conciseness:
v-modelis written directly as an instruction, whereasv-bindtypically requires specifying the exact attribute (e.g.,v-bind:srcorv-bind:class). In shorthand form,v-bindcan be used with a colon (:), such as:src="imageSrc".
Understanding the distinct purposes and mechanisms of these directives is essential for effectively leveraging Vue to build interactive interfaces.