Home > Web Front-end > JS Tutorial > body text

VueJs for Beginner VueJs Part Data Binding

Patricia Arquette
Release: 2024-09-29 16:50:29
Original
857 people have browsed it

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

Copy after login

Binding with Directives

v-bind: Bind HTML attributes to data.

<img v-bind:src="imageUrl" alt="Example Image">
Copy after login

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" />
Copy after login

This is equivalent to:

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

Here’s how you can use :value and @input separately:


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


Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

This can be shortened to:

<button @click="handleClick">Click me!</button>
Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template