Vue.js Computed Properties

If you're just getting started with this series of Vue.js posts, you should start with the Vue.js Starter Page.

Computed Properties are very similar to using Vue.js methods but the computed properties are much more efficient.

The difference? It's a big one, and here it is: All methods will run in the Vue.js instance when just one of the methods is called, but the computed properties are smarter and will only run the requested computed property method when requested.

The call to a regular method is seen down on line XX. The call to a computed property is down on line XX. You call a method (which fires all of the methods) using parens () but you omit the parens when calling a computed property method.

Noteworthy: Originally I built this demo with both methods and computed properties stated on the page, which failed because even though "Computed" and "Methods" in the Vue.js object are different data objects I had them named the same "addToA" and "addToB". Vue.js didn't like that and didn't run, so I left the code intact to show this but commented it out.

Computed Properties

A - {{a}}

B - {{b}}

COMPUTED PROPERTY: Age + A = {{addToA}}

COMPUTED PROPERTY: Age + B ={{addToB}}



<!doctype html>

<html>
<head><meta charset="UTF-8"><title>VueJS</title>
<script src="https://unpkg.com/vue@2.3.0"></script>

</head>
<body>

<div id="app"> <h3>Computed Properties</h3> <label>Name: </label> <button v-on:Click="a++">Add to A</button> <button v-on:Click="b++">Add to B</button> <p>A - {{a}}</p> <p>B - {{b}}</p> <!--<p>METHOD: Age + A ={{addToA()}}</p> <p>METHOD: Age + B ={{addToB()}}</p>--> <p>COMPUTED PROPERTY: Age + A = {{addToA}}</p> <p>COMPUTED PROPERTY: Age + B ={{addToB}}</p> </div> </body> <script> var vm = new Vue({ el:'#app', data: { age: 20, a:0, b:0 }, methods: { /*addToA:function(){ console.log('addToA'); return this.a + this.age; }, addToB:function(){ console.log('addToB'); return this.b + this.age; }*/ }, computed: { addToA:function(){ console.log('addToA'); return this.a + this.age; }, addToB:function(){ console.log('addToB'); return this.b + this.age; } } }) </script> </html>

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/vue-js/vue-js-computed-properties/