- [Instructor] In this video we're going to look
at computed properties which can make our templates easier
to understand by stripping out code.
This product size class that we've written here,
isn't the most complex job of script ever written
but it is kind of awkward.
And if we need to use this more than once,
even something this tiny,
could be a little problematic to maintain.
Like if the css class that powers it were to change,
we'd have to change it in more than one place.
What we want to do is take this little bit of complexity,
out of the template and bring it into our code.
So I'm going to copy this expression.
Make sure I get the whole thing here.
Copy that expression and switch over to app.js.
Now you might think this being Java Script that,
what I could do is just add a function to the data object.
Say call it sizeClass, and then have a function here
that calculates whatever it is
that I want that sizeClass to be.
But that's not going to work in view.
The data in our data object, need to be plain objects,
because if view transparently changes them into getter
and setter functions which power its reactivity.
So instead, what we need to do is,
add a computed property to the view instance.
It's another object at the top level.
Same level as el an data here, it's called computed.
Its keys are the names of the properties
that we want to use in our templates
and the values are the functions that do the computation.
So I'm going to add one called sizeClass.
This will be a function and what I need
to do is return what I want this to be.
So I want to return this data and I need
to change selectedSize to this.selectedSize.
So we're referring to the view instance.
Otherwise this is all I need to do.
So I can save this.
It's called sizeClass so I'll copy that,
come back over to my index.html and paste it in.
So now I can use this computed property,
the same way I use any other reactive data.
This is much simpler to read and it's much clearer what
this is suppose to do at a glance.
So now if I switch over to my browser and refresh,
I'm going to open up my DevTools with command option i,
switch to view tab and here on my root component,
I see that I have my computed size class
and it updates as I change the size.
So I end up with a much cleaner template
and another nice benefit of computed properties is
that the values are cashed and they're only recalculated,
if whatever they depend on changes.
So if my sizes array changes but my selected size doesn't,
this doesn't need to be recalculated.
He was clever enough to handle that for you.
So computed properties are a really handy way
to get expressions that are at least somewhat complex
or maybe just unsightly
out of your templates and into your code.