In the previous blog/article, we learned how to create, import, and use components. This time, we will explore data binding in components.
Using Data within Components
Defining Data in a Component
Data is defined in the data()
function and returned as an object.
Here's an example:
data() {
return {
message: 'Hello World!'
};
}
Binding with Directives
v-bind:
Bind HTML attributes to data.
<img v-bind:src="imageUrl" alt="Example Image">
v-model:
The v-model directive is used for two-way data binding on form inputs. It keeps the input value in sync with the Vue instance data. Essentially, v-model combines @input (which listens for changes) and :value (which sets the input value). For example:
<input v-model="message" />
This is equivalent to:
<input :value="message" @input="message = $event.target.value" />
Here’s how you can use :value and @input separately:
<!-- Using :value -->
<input :value="message" @input="message = $event.target.value" />
<!-- This displays the current message, and updates the message variable when the input changes. -->
The v-if
directive conditionally renders elements based on a boolean value. If the condition is true, the element will be rendered; if false, it won’t. For example:
<p v-if="isVisible">This is visible!</p>
The v-for
directive is used to loop through an array or an object to render elements. Each element can be given a unique key for better performance. For example:
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
v-on
The v-on
directive is used to listen for events on elements. You can use the shorthand @
for convenience. For example:
<button v-on:click="handleClick">Click me!</button>
This can be shortened to:
<button @click="handleClick">Click me!</button>
Top comments (0)