⚠️ This lesson is retired and might contain outdated information.

Use Vue.js Component Computed Properties

Greg Thoman
InstructorGreg Thoman
Share this video with your friends

Social Share Links

Send Tweet

You can add computed properties to a component to calculate a property on the fly. The benefit of this over invoking a method is that computed properties are cached based on their dependencies.

[00:00] Here we have a list of dinosaur species along with their quantities. Let's use computed properties to aggregate their totals. For total dinosaurs, let's use the property total dinos and for total species, we'll use total species.

[00:14] Let's add these two properties to our data struct and default them to zero. After our methods block, let's add a section called computed. The properties in the computed block will override those in data.

[00:26] We'll create a new method called total dinos. In that method, let's create a variable called sum and another one for items. For each item, let's add its quantity to sum. Then let's return sum. For total species, we'll return the length of our items array.

[00:43] Let's create a way to track how many times these computed properties are being called. Let's add a span to our template with the property dinos updated and another span with species updated. We'll default those to zero in our data struct.

[00:58] In our total dinos method, let's increment this.dinos updated. In total species, we'll increment this.species updated. Now we can watch the updated properties change when those computed properties get called.