CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

05 February, 2021

Vue.js Reactivity System

 Programing Coderfunda     February 05, 2021     Vue.js Tutorial     No comments   

 

Vue.js Reactivity System

The reactivity system is one of the most distinctive features of Vue.js. In Vue.js, models are plain JavaScript objects. When we have to modify the models, the views are updated. This makes state management simple and intuitive, but it's also essential to understand how it works to avoid some common upcoming problems. Here, we will see how to deal with these problems by using the reactivity system.

How does it work?

If you pass a plain JavaScript object to a Vue.js instance as its data option, you will see that Vue.js makes this pass through all of its properties and convert them to getter/setters using Object.defineProperty.

This is an un-shimmable and an ES5-only feature. Because of this feature, Vue doesn't support IE8 and below versions.

The getter and setters are not visible to the user, but under the hood, they make Vue.js able to perform dependency-tracking and change-notification when you have to change or access the property. You can see the getter/setters properties changes on the browser's console. If you want to see them, you have to install vue-devtools for a more inspection-friendly interface.

Every component instance has a corresponding watcher instance. This is used to record the properties "touched" during the component's render as dependencies. After that, when a dependency's setter is triggered, it notifies the watcher, which re-render the component in turn.

Vue.js Reactivity System

Vue.js Reactive Interface

Vue.js provides us an option to add reactivity to the dynamically added properties. Suppose, we have already created Vue.js instance and we want to add the watch property. See the following example:

Example:

Index.html file:

  1. <html>    
  2.    <head>    
  3.       <title>Vue.js Reactive Interface</title>    
  4.       <link rel="stylesheet" href="index.css">    
  5.         <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>    
  6.     </head>    
  7.     <body>    
  8.       <div id = "reactivity_1">  
  9.          <p style = "font-size:25px;">Counter: {{ counter }}</p>  
  10.          <button @click = "counter++" style = "font-size:25px;">Click Here</button>  
  11.       </div>   
  12.       <script src="index.js"></script>    
  13.    </body>    
  14. </html>   

Index.js file:

  1. var vm = new Vue({  
  2.             el: '#reactivity_1',  
  3.             data: {  
  4.                counter: 1  
  5.             }  
  6.          });  
  7.          vm.$watch('counter', function(nval, oval) {  
  8.             alert('Counter is incremented :' + oval + ' to ' + nval + '!');  
  9.          });  
  10.          setTimeout(  
  11.             function(){  
  12.                vm.counter = 10;  
  13.             },1000  
  14.          )  

Let's use a simple CSS file to make the output more attractive.

Index.css file:

  1. html, body {  
  2.     margin: 5px;  
  3.     padding: 0;  
  4. }  

After the execution of the program, you will see the following output:

Output:

Vue.js Reactivity System
Vue.js Reactivity System

When you click on the "Click Here" button, the counter will be incremented. You will see a pop-up output or an alert message that shows the counter property's changed value.

See the following output after we have clicked on the "Click here" button.

Vue.js Reactivity System
Vue.js Reactivity System

Example Explanation

In the above example, we have defined a property counter that is set to 1 in the data object. When you click on the "Click Here" button, the counter will be incremented.

After creating the Vue.js instance, we have to add the watch property to it.Use the following code to add it:

  1. vm.$watch('counter', function(nval, oval) {  
  2.    alert('Counter is incremented :' + oval + ' to ' + nval + '!');  
  3. });   

We have used the $watch property to add watch outside the Vue instance. We have also added an alert used to show the value change for the counter property. A timer function is also added named setTimeout to set the counter value to 10.

  1. setTimeout(  
  2.    function(){  
  3.       vm.counter = 10;  
  4.    },1000  
  5. );  

Whenever you click the button, the counter will be changed, and the alert from the watch method will get fired.

Add properties at Runtime.

It is the best way always to declare the properties, which need to be reactive upfront in the Vue.js instance because Vue.js cannot detect property addition and deletion.

If you want to add properties at run time, you have to make use of Vue global, Vue.set, and Vue.delete methods.

Vue.set

This is used to set a property on an object. This is used to overcome the limitation that Vue.js cannot detect property additions.

Syntax

  1. Vue.set( target, key, value )  

Here,

target: It can be an object or an array.

key: It can be a string or number.

value: It can be any type.

Let's take a simple example to understand the concept of Vue.set.

Example:

Index.html file:

  1. <html>    
  2.    <head>    
  3.       <title>Vue.js Reactive Interface</title>    
  4.       <link rel="stylesheet" href="index.css">    
  5.         <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>    
  6.     </head>    
  7.     <body>    
  8.       <div id = "reactivity_1">  
  9.          <p style = "font-size:25px;">Counter value: {{ products.id }}</p>  
  10.          <button @click = "products.id++" style = "font-size:25px;">Click Here</button>  
  11.       </div>  
  12.       <script src="index.js"></script>    
  13.    </body>    
  14. </html>    

Index.js file:

  1. var myproduct = {"id":1, name:"shirt", "price":"1000.00"};  
  2.          var vm = new Vue({  
  3.             el: '#reactivity_1',  
  4.             data: {  
  5.                counter: 1,  
  6.                products: myproduct  
  7.             }  
  8.          });  
  9.          vm.products.qty = "1";  
  10.          console.log(vm);  
  11.          vm.$watch('counter', function(nval, oval) {  
  12.             alert('Counter is incremented :' + oval + ' to ' + nval + '!');  
  13.          })   

After the execution of the program, you will see the following output:

Output:

Vue.js Reactivity System

Here, you will see that the counter value will be increased every time when you click on the "Click Here" button. See the following output. Here, we have clicked button for 5 times.

Vue.js Reactivity System

Example Explanation

In the above example, we have created a variable named myproduct at the start using the following code:

  1. var myproduct = {"id":1, name:"shirt", "price":"1000.00"};  

It is given to the data object in Vue.js instance as follows:

  1. var vm = new Vue({  
  2.             el: '#reactivity_1',  
  3.             data: {  
  4.                counter: 1,  
  5.                products: myproduct  
  6.             }  
  7.          });  

Suppose, you have to add one more property to the myproduct array, after the Vue.js instance is created. You can do this by using the following code:

  1. vm.products.qty = "1";   

If you see the output on the console, you will find that in products list, the quantity will be added. The get/set methods, which basically add reactivity, are available for the id, name, and price, and not available for the qty.

So, you can see that the reactivity cannot be achieved by just adding the vue object. In Vue.js, you have to create its all properties at the start. If you want to do it later, we can use Vue.set. See an other example where all the properties are added later.

Example:

Index.html file:

  1. <html>    
  2.    <head>    
  3.       <title>Vue.js Reactive Interface</title>    
  4.       <link rel="stylesheet" href="index.css">    
  5.         <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>    
  6.     </head>    
  7.     <body>    
  8.       <div id = "reactivity_1">  
  9.          <p style = "font-size:25px;">Counter value: {{ products.id }}</p>  
  10.          <button @click = "products.id++" style = "font-size:25px;">Click Here</button>  
  11.       </div>  
  12.       <script src="index.js"></script>    
  13.    </body>    
  14. </html>   

Index.js file:

  1. var myproduct = {"id":1, name:"shirt", "price":"1000.00"};  
  2.          var vm = new Vue({  
  3.             el: '#reactivity_1',  
  4.             data: {  
  5.                counter: 1,  
  6.                products: myproduct  
  7.             }  
  8.          });  
  9.          Vue.set(myproduct, 'qty', 1);  
  10.          console.log(vm);  
  11.          vm.$watch('counter', function(nval, oval) {  
  12.             alert('Counter is incremented :' + oval + ' to ' + nval + '!');  
  13.          })  

In the above example, we have used Vue.set to add the qty to the array using the following code:

  1. Vue.set(myproduct, 'qty', 1);   

If you run this example on the console, you will see that the get/set for qty is added using Vue.set method.

Vue.delete

The Vue.delete function is used to delete the property dynamically. This is also used to overcome the limitation that Vue.js cannot detect property deletion.

Syntax:

  1. Vue.delete( target, key )  

Here,

target: It is used to specify an object or an array.

key: It is used to specify a string or a number.

Let's see an example to demonstrate how to delete any property dynamically in Vue.js using Vue.delete function.

Example

Index.html file:

  1. <html>    
  2.    <head>    
  3.       <title>Vue.js Reactive Interface</title>    
  4.       <link rel="stylesheet" href="index.css">    
  5.         <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>    
  6.     </head>    
  7.     <body>    
  8.       <div id = "reactivity_1">  
  9.          <p style = "font-size:25px;">Counter value: {{ products.id }}</p>  
  10.          <button @click = "products.id++" style = "font-size:25px;">Click Here</button>  
  11.       </div>  
  12.       <script src="index.js"></script>    
  13.    </body>    
  14. </html>    

Index.js file:

  1. var myproduct = {"id":1, name:"shirt", "price":"1000.00"};  
  2.          var vm = new Vue({  
  3.             el: '#reactivity_1',  
  4.             data: {  
  5.                counter: 1,  
  6.                products: myproduct  
  7.             }  
  8.          });  
  9.           Vue.delete(myproduct, 'price');  
  10.          console.log(vm);  
  11.          vm.$watch('counter', function(nval, oval) {  
  12.             alert('Counter is incremented :' + oval + ' to ' + nval + '!');  
  13.          })    

In the above example, we have used the Vue.delete function to delete the price from the array by using the following code:

  1. Vue.delete(myproduct, 'price');  

When you see the output of the above example on the console, you will see that only the id and name are visible on the console as the price is deleted. We will also notice that the get/set methods are deleted. 

 

Source by : javatpoint.com

 


  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Getting started with Vue.js Getting started with Vue.jsIn the previous chapter, we have seen several ways to use and install Vue.js in your project. In this article, we sha… Read More
  • Vue.js InstanceVue.js InstanceTo start a Vue application, you have to create a new Vue instance by using the Vue function. Whenever we create a new Vue project, the … Read More
  • Vue.js TemplateVue.js TemplateIn the previous Vue.js Instance chapter, we have learned how to get an output in the form of text content on the screen. In this chapte… Read More
  • Vue.js Declarative RenderingVue.js Declarative RenderingIn Vue.js, there is a system in the core that enables us to declaratively render data to the DOM using simple, straightfor… Read More
  • Vue.js Conditions & LoopsVue.js Conditions & LoopsConditions and Loops are used in all programming languages to provide repetitive control structures. They can repeat one … Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh
    I had follow these steps to install an configure firebase to my cordova project for cloud messaging. https://medium.com/@felipepucinelli/how...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...
  • Cashier package and Blade files
    I'm a little confused about this Cashier package. I installed it using the Laravel website (with composer), but noticed there's no...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Customize URL Handling with Laravel's Macroable URI Class - 5/13/2025
  • Use Passkeys in Your Laravel App - 5/13/2025
  • Laravel Seeder Generator - 5/12/2025
  • Improve HTTP Error Testing with Laravel's requestException() Method - 5/12/2025
  • Track Metrics Effortlessly with Laravel's Context Increment and Decrement Methods - 5/4/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda