Home >Web Front-end >JS Tutorial >VueJs for Beginner VueJs Part Data Binding

VueJs for Beginner VueJs Part Data Binding

Patricia Arquette
Patricia ArquetteOriginal
2024-09-29 16:50:29891browse

VueJs for Beginner VueJs Part  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!'
  };
}

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:


<input :value="message" @input="message = $event.target.value" />


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>

The above is the detailed content of VueJs for Beginner VueJs Part Data Binding. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn