Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Vue.js Component Computed Properties

    Greg ThomanGreg Thoman

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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.

    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.

    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.

    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.

    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.