Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptWhat is the difference between one-way data flow and two-way data binding...

What is the difference between one-way data flow and two-way data binding in vue.js?

Vue.js is an open-source front-end JavaScript framework for building user interfaces and single-page applications. It follows Model-View-ViewModel (MVVM) architecture pattern. Vue.js has many in-built directives for DOM manipulation such as v-bind, v-on, v-model, etc. In this article, we will learn about the one-way data binding & two-way data binding in vue.js, along with knowing the differences between them & their basic implementations through the illustration

Model-View-Viewmodel (MVVM) Pattern in Vue.js: MVVM pattern has some similarities with the MVP(Model-View-Presenter) design pattern as the Presenter role is played by the ViewModel. However, the drawbacks of the MVP pattern has been solved by MVVM. It suggests separating the data presentation logic(Views or UI) from the core business logic part of the application.

Model-View-ViewModel pattern

The separate code layers of MVVM are:

  • View: View is a Presentation layer that User Interface structure represents the DOM, The Document Object Model (DOM) that is managed by Vue instances.

 

Syntax:

<div>
    <p> {{ name }} </p>
<div>
  • Model: Model is a Business-Logic Layer containing plain javascript objects or Data model objects that become reactive when created by Vue instances. Whenever objects changed, the View also updated simultaneously.

Syntax:

data : { name: "neveropen" }
  • ViewModel: View-Model layer that projects and transforms Model objects for state changes. View layer listens to that property changes and renders in DOM. It is a bridge between the Model and View for creating Vue instance with synchronized objects. Vue instances created by Vue() Constructor. Vue directives are used to help Data manipulations and DOM listeners in Vue instances.

Syntax:

const app = new Vue( {....} );

Data Binding is one of the most important features in web applications which is useful to sync the values updated by the user during the interaction with the web pages. It is a process of binding the data objects that communicate between HTML and the business logic. In Vue.js, the data binding provides fast and automatic communication between Data Model ( Vue Component ) and the View(Presentation layer). Vue.js provides both the one-way data flow & two-way data flow binding for web applications. In Vue.js, there is no need to write complex code for two-way data binding, unlike other frameworks.

Types of Data Binding:

  • One-way data binding
  • Two-way data binding

The below diagram illustrates the basic concept of data binding & their types:

 

One-Way data binding: In one-way data flow, the DOM( Document Object Model ) does not update automatically when the data Model changes, so we need to write some custom code to update/trigger it when the data model is changed. If the user needs to modify/manipulate the data, View(presentation layer) needs to send the communication through events. The events will trigger the Model(business-logic layer) and update the context.

Let’s see the Implementations of one-way data binding in Vue.js:

  • String Interpolation: Use double curly braces for binding any data variable, and initialize the data objects through Vue Components. The {{ }} double curly braces stands for property binding.

Syntax:

<p>{{name-of-variable}}</p>

Variables are created and defined inside the data model.

<script>
    data : { text1: "Geeks For Geeks" }
</script>

It will bind the value inside double curly braces of <p> element at the DOM presentation layer when the Vue instance is loaded.

<p>{{text1}}</p>

once text1 binds with DOM we can’t change the value of text1 due to one-way data flow, still, you can change the value with help of event binding. Events are used for listening to DOM elements when it’s changed.

  • v-bind directive: Also Use the v-bind directive for binding styles and class attributes, it uses one-way data binding that data always flows in a single direction. It helps to bind CSS styles for the data elements in DOM.

Syntax:

<span v-bind:style="{ color: 'green' }">{{name-of-variable}}</span>

Below Code example will display the text1 in DOM using a one-way data flow for the text with green color styles and bold format.

<script>
    data : { text1: "neveropen" }
</script>
<h1 v-bind:style="{ color: 'green' }">{{text1}}</h1>
  • v-once directive: If we want to avoid data objects re-rendering from the DOM changes, use the v-once directive. It will help data to render only once.

Syntax:

<span v-once> 
    This content can bind only once : {{text2}}
</span>

Example 1: In the below example, we are binding three text attributes using a one-way data flow. The first one is text1 which represents the input from the text box, the Event handler will help that text will modify in DOM. Enter a text in the text box field, it will update the text in string interpolation of {{text1}} when the button is clicked. The text2 represents once in the DOM with help of the v-once directive, we cannot change this text once rendered by the Vue component. if we want to avoid re-rendering from the DOM changes, this directive will help to render only once. The text3 represents the header and it uses the v-bind directive for binding text styles according to the given color.

  • index.html

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        One-Way data binding in VueJS
    </title>
    <script src=
    </script>
</head>
  
<body>
    <div id='firstApp'>
        <h1 v-bind:style="neveropen">
            {{text3}}
        </h1>
        <input ref="inputText" 
               name="inputText" 
               type="text" 
               placeholder='Type Text Here' />
        <button v-on:click="firstBtn">
            Submit
        </button>
        <h3>
            This is one way binding : {{text1}}
        </h3>
  
        <!--We can avoid re-rendering the data model,
            then use v-once directive -->
        <h3 v-once>
            This content can bind only once : {{text2}}
        </h3>
    </div>
    <script src='app.js'></script>
</body>
  
</html>


  • app.js

Javascript




const firstApp = new Vue({
    el: '#firstApp',
    data: {
        text1: 'Change the text by Event handler',
        text2: 'Never Change',
        text3: 'neveropen',
  
        neveropen: {
            color: "green",
            fontSize: "30px",
            fontWeight: "bold"
        }
    },
    methods: {
        firstBtn: function () {
            const message = this.$refs.inputText.value;
            this.text1 = message;
            this.text2 = message;
  
        }
    }
});


Output:

One-way data binding

Two-Way data binding: In two-way data binding, DOM automatically updates when the data Model is changed. It will help you to sync your data with your DOM without triggering events. If the data is modified/manipulated by the user, simultaneously the changes will be reflected directly to both the business logic(Model) and the presentation layer(View). Vue.js using v-model directive for two-way data binding. The v-model directive is used for reactive data binding, as it is used internally inside the HTML attributes which can bind along with data enclosed by double curly braces.

Syntax: Whenever we enter a value in input field, it will rendering automatically inside <p> tag

<input v-model="name" />
<p>{{name}}</p>

Example 2: In the below example, we are binding data attributes using the v-model directive in the input Textbox and radio Buttons for two-way data flow. The v-model elements render simultaneously when the input fields of the text box and radio buttons will be changed. Additionally, we use a Reset button for clearing data fields which are triggered by a mouse click event. Use HTML code “&#11088 ” for add the stars ⭐ icon.

  • index.html

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Two-way binding in VueJS
    </title>
    <script src=
    </script>
</head>
  
<body>
    <div id='firstApp'>
        <input v-model="sampleText" 
               name="name" 
               type="text" 
               placeholder='Type Text Here' />
        <button v-on:click="firstBtn">
            Reset
        </button>
        <h1>
            This is Two way binding: {{sampleText}}
        </h1>
        <p>rate this content</p>
  
        <label>
            <input type="radio" 
                   value="⭐ good" 
                   v-model="rating" />good
        </label>
        <label>
            <input type="radio" 
                   value="⭐⭐ very good" 
                   v-model="rating" />
            very good
        </label>
        <label>
            <input type="radio" 
                   value="⭐⭐⭐ excellent" 
                   v-model="rating" />
            excellent
        </label>
          
        <!-- Two-way data binding to rendering "rating" data model
             automatically using v-model directive in input field --->
        <p v-if=rating>
            Rating : {{rating}}
        </p>
    </div>
    <script src='app.js'></script>
</body>
  
</html>


  • app.js

Javascript




const firstApp = new Vue({
    el: '#firstApp',
    data: {
        sampleText: '',
        rating: ''
    },
      
    // This method will clears the data 
    // fields using button event click 
    methods: {
        firstBtn: function () {
            this.sampleText = '';
            this.rating = '';
        }
    }
});


Output:

Two-way data binding

Difference between one-way data & two-way data binding:

One-way data binding

Two-way data binding 

It optimizes the update performance by rendering the element and component unidirectional.

It optimizes the update performance by rendering the element and component are bidirectionally synchronized 

The data is just bound to the DOM, using custom code to trigger DOM changes

data is bound from DOM. When DOM gets changed, the data also gets changed.

It follows static binding in the data model

It follows Dynamic binding in the data model

UI may need an event handler to update the data model.

It makes reactive binding between DOM and the data model

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments