Open In App

Vue.js Computed Properties

Improve
Improve
Like Article
Like
Save
Share
Report

Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries.

In Vue.js, any data value can be output using parentheses. However, this can host small computations since it is limited to a single JavaScript expression, and also that templates should only be concerned with displaying data to the user and not performing any logic computations. To avoid this limitation of a single expression and have more declarative templates, we use computed properties of Vue.js. The computed value follows the same old interpolation, but the computation logic is defined in JavaScript.

Example 1:

index.html




<html>
<head>
    <script src=
      </script>
</head>
<body>
    <div id='parent'>
          
<p>{{ fullName }}</p>
  
    </div>
    <script src='app.js'></script>
</body>
</html>


app.js




const parent = new Vue({
  el: '#parent',
  data: {
    fName: 'Aiser',
    lName: 'Wold'
  },
  
  computed: {
    fullName: function () {
      return `Full Name :
        ${this.fName} ${this.lName}`
    }
  }
})


Output:

Computed Properties

Example 2:

index.html




<html>
<head>
    <script src=
      </script>
</head>
<body>
    <div id='parent'>
        <h2>Animal Helping NGO</h2>
          
<p><strong>Total Members :</strong
          {{ totalMembers }}
          </p>
  
          
<p><strong>Donations from Male members :
          </strong> {{ maleDonation }}
          </p>
  
          
<p><strong>Donations from female members :
          </strong> {{ femaleDonation }}
          </p>
  
    </div>
    <script src='app.js'></script>
</body>
</html>


app.js




const parent = new Vue({
    el: '#parent',
    data: {
        mMembers: ['Arun', 'Raj', 'Kabir',
                   'Santanu','Aiser','Mikie'],
        fMembers: ['Tina','Jagriti','Nupur',
                   'Nancy','Rinkle']
    },
  
    computed: {
        totalMembers: function() {
            return this.mMembers.length + 
                   this.mMembers.length
        },
        maleDonation: function() {
            return this.mMembers.length * 100;
        },
        femaleDonation: function() {
            return this.fMembers.length * 50
        }
    }
})


Output:

computed properties

Reference:https://012.vuejs.org/guide/computed.html



Last Updated : 22 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads