VueJs for Beginner 2024 #VueJs Part 3 : Data Binding

kyydev

KyDev

Posted on September 29, 2024

VueJs for Beginner 2024 #VueJs Part 3 : Data Binding

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!'
  };
}

Enter fullscreen mode Exit fullscreen mode

Binding with Directives

v-bind: Bind HTML attributes to data.

<img v-bind:src="imageUrl" alt="Example Image">
Enter fullscreen mode Exit fullscreen mode

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" />
Enter fullscreen mode Exit fullscreen mode

This is equivalent to:

<input :value="message" @input="message = $event.target.value" />
Enter fullscreen mode Exit fullscreen mode

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. -->
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

This can be shortened to:

<button @click="handleClick">Click me!</button>
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
kyydev
KyDev

Posted on September 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related