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

28 December, 2020

Vue.js Computed Properties

 Programing Coderfunda     December 28, 2020     Vue.js Tutorial     No comments   

Vue.js Computed Properties 

In Vue.js, computed properties are used when we have to handle complex logic and operations. Computed properties are just like methods but with some differences.

We have successfully used in-template expressions in previous examples. They are very convenient, but the in-template expressions are mainly used for simple operations. If you have to put a heavy and complex logic in your templates, it can be bloated and hard to maintain.

For example:

  1. <div id="example">  
  2.   {{ message.split('').reverse().join('') }}  
  3. </div>  

Here you can see that the template is not as simple and declarative as before. It looks more complex, and you have to look at it for a second before realizing that it displays the message in reverse. This problem may get worse when you have to use the reversed message in your template repeatedly.

Let's take some easy examples to make computed properties concept clear and easy to understand. This can also make you able to decide when to use methods and when to use computed properties.

See the following examples to understand the concept of computed properties:

Example1

Index.html file:

  1. <html>  
  2.    <head>  
  3.       <title>Vue.js Computed Property</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="com_props">  
  9.   This is the Original message:<h2> {{ message }}</h2>  
  10.   This is the Computed reversed message: <h2> {{ reversedMessage }}</h2>  
  11. </div>  
  12.       <script src="index.js"></script>  
  13.    </body>  
  14. </html>  

Index.js file:

  1. var vm = new Vue({  
  2.   el: '#com_props',  
  3.   data: {  
  4.     message: 'Hello JavaTpoint'  
  5.   },  
  6.   computed: {  
  7.     // a computed getter  
  8.     reversedMessage: function () {  
  9.       // `this` points to the vm instance  
  10.       return this.message.split('').reverse().join('')  
  11.     }  
  12.   }  
  13. })  

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 Computed Properties

Example explanation

In the above example, we have declared a computed property reversedMessage. Here the provided function is used as the getter function for the property reversedMessage. The value of reversedMessage is always dependent on the value of message property.

  1. data: {  
  2.     message: 'Hello JavaTpoint'  
  3.   },  
  4.   computed: {  
  5.     // a computed getter  
  6.     reversedMessage: function () {  

Example 2

Let's take another example. In this example, you can enter your data in a form structure and see the result of computer property. See the following example:

Index.html file:

  1. <html>  
  2.    <head>  
  3.       <title>Vue.js Computed Property</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 = "com_props">  
  9.          FirstName : <input type = "text" v-model = "firstname" /> <br/><br/>  
  10.          LastName : <input type = "text" v-model = "lastname"/> <br/><br/>  
  11.          <h2>My name is {{firstname}} {{lastname}}</h2>  
  12.          <h2>Retrieve name by using computed property : {{getfullname}}</h2>  
  13.       </div>  
  14.       <script src="index.js"></script>  
  15.    </body>  
  16. </html>  

Index.js file:

  1. var vm = new Vue({  
  2.    el: '#com_props',  
  3.    data: {  
  4.       firstname :"",  
  5.       lastname :"",  
  6.       birthyear : ""  
  7.    },  
  8.    computed :{  
  9.       getfullname : function(){  
  10.          return this.firstname +" "+ this.lastname;  
  11.       }  
  12.    }  
  13. })  

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 Computed Properties

Example explanation

In the above example, we have created two textboxes named Firstname and Lastname. These textboxes are bound using properties firstname and lastname.

Now, we have called computed method getfullname, which returns the firstname and the lastname entered.

  1. computed :{  
  2.    getfullname : function(){  
  3.       return this.firstname +" "+ this.lastname;  
  4.    }  
  5. }  

When we type in the textbox, the function returns the same after the changes in properties' firstname or lastname. Thus, with the help of computed we don't have to do anything specific, such as remembering to call a function. With computed property, it gets called by itself as the properties used inside changes, i.e. firstname and lastname.

Difference between a method and a computed property

In the above examples, we have learned about computed properties. Now, let's learn about the difference between a method and a computed property. We know that both are objects, and there are functions defined inside, which returns a value.

In the case of computed properties, we call it a property while we call it a function in the case of method. Let's see an example to understand the difference between method and computed property.

Index.html file:

  1. <html>  
  2.    <head>  
  3.       <title>Vue.js Computed Property</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 = "com_props">  
  9.          <h2 style = "background-color:gray;">Random No from computed property: {{getrandomno}}</h2>  
  10.          <h2>Random No from method: {{getrandomno1()}}</h2>  
  11.          <h2  style = "background-color:gray;">Random No from computed property: {{getrandomno}}</h2>  
  12.          <h2  style = "background-color:gray;">Random No from computed property: {{getrandomno}}</h2>  
  13.          <h2>Random No from method: {{getrandomno1()}}</h2>  
  14.       </div>  
  15.       <script src="index.js"></script>  
  16.    </body>  
  17. </html>  

Index.js file:

  1. var vm = new Vue({  
  2.             el: '#com_props',  
  3.             data: {  
  4.                name : "helloworld"  
  5.             },  
  6.             methods: {  
  7.                getrandomno1 : function() {  
  8.                   return Math.random();  
  9.                }  
  10.             },  
  11.             computed :{  
  12.                getrandomno : function(){  
  13.                   return Math.random();  
  14.                }  
  15.             }  
  16.          })  

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 Computed Properties

Example Explanation

In the above example, we have created a method named getrandomno1 and a computed property with a function name getrandomno. In this example, we are using Math.random() to get back result in the form of random numbers. We have called the method and computed property many times to see the difference.

Here, you can see that the random numbers returned from the computed property remain the same every time irrespective of the number of times it is called. This means every time it is called; the last value is updated for all. On the other hand, for a method, it is a function, so it returns a different value every time it is called.

Get/Set in Vue.js Computed Properties

Let's see how to use get/set functions in Vue.js computed properties. See the following example:

Index.html file:

  1. <html>  
  2.    <head>  
  3.       <title>Vue.js Computed Property</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 = "com_props">  
  9.          <input type = "text" v-model = "fullname" />  
  10.          <h1>{{firstName}}</h1>  
  11.          <h1>{{lastName}}</h1>  
  12.       </div>  
  13.       <script src="index.js"></script>  
  14.    </body>  
  15. </html>  

Index.js file:

  1. var vm = new Vue({  
  2.             el: '#com_props',  
  3.             data: {  
  4.                firstName : "Alex",  
  5.                lastName : "Junior"  
  6.             },  
  7.             methods: {  
  8.             },  
  9.             computed :{  
  10.                fullname : {  
  11.                   get : function() {  
  12.                      return this.firstName+" "+this.lastName;  
  13.                   }  
  14.                }  
  15.             }  
  16.          })  

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

Output:

Vue.js Computed Properties

In the above example, we have defined a computed property input box that is bound to fullname. It returns a function called get and gives the fullname as output, i.e., the first name and the last name.

  1. <h1>{{firstName}}</h1>  
  2. <h1>{{lastName}}</h1>  

Now, you can see that if you change the name in the textbox, the result is not reflected in the output. See the following image.

Output:

Vue.js Computed Properties

To resolve this issue, we have to add the setter function in the fullname computed property.

Add the following set function in the fullname computed property:

  1. computed :{  
  2.    fullname : {  
  3.       get : function() {  
  4.          return this.firstName+" "+this.lastName;  
  5.       },  
  6.       set : function(name) {  
  7.          var fname = name.split(" ");  
  8.          this.firstName = fname[0];  
  9.          this.lastName = fname[1]  
  10.       }  
  11.    }  
  12. }  

See the following example:

Index.html file:

  1. <html>  
  2.    <head>  
  3.       <title>Vue.js Computed Property</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 = "com_props">  
  9.          <input type = "text" v-model = "fullname" />  
  10.          <h1>{{firstName}}</h1>  
  11.          <h1>{{lastName}}</h1>  
  12.       </div>  
  13.       <script src="index.js"></script>  
  14.    </body>  
  15. </html>  

Index.js file:

  1. var vm = new Vue({  
  2.             el: '#com_props',  
  3.             data: {  
  4.                firstName : "Alex",  
  5.                lastName : "Junior"  
  6.             },  
  7.             methods: {  
  8.             },  
  9.             computed :{  
  10.                fullname : {  
  11.                   get : function() {  
  12.                      return this.firstName+" "+this.lastName;  
  13.                   },  
  14.                   set : function(name) {  
  15.                      var fname = name.split(" ");  
  16.                      this.firstName = fname[0];  
  17.                      this.lastName = fname[1]  
  18.                   }  
  19.                }  
  20.             }  
  21.          });  

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

Output:

Vue.js Computed Properties

Now, if you edit the textbox after running the code, the updated name will be displayed in the browser. The firstname and the lastname are updated here because of the set function. The get function returns the firstname and lastname, while the set function updates it if you edit anything in the textbox.

See the output after editing.

Output:

Vue.js Computed Properties
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • Features CodeIgniter
    Features CodeIgniter There is a great demand for the CodeIgniter framework in PHP developers because of its features and multiple advan...
  • Laravel Breeze with PrimeVue v4
    This is an follow up to my previous post about a "starter kit" I created with Laravel and PrimeVue components. The project has b...
  • Credit card validation in laravel
      Validation rules for credit card using laravel-validation-rules/credit-card package in laravel Install package laravel-validation-rules/cr...
  • Fast Excel Package for Laravel
      Fast Excel is a Laravel package for importing and exporting spreadsheets. It provides an elegant wrapper around Spout —a PHP package to ...

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)

Loading...

Laravel News

Loading...

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