Just like with the options API the composition API lets us create computed properties Let's make a computed property on our yummy meal component that formats the dollar amount of our meal for us We'll do this first with the options API and then switch it over to use the composition API Just so that you can see how simple the transition is First we'll provide the computed option and under it define a function called pricePretty. And then we'll just add the dollar sign character and the change after the $5 price. Sure, this doesn't really account for any internationalization or anything, but you get the picture. Finally, we'll put it to good use in the template.
Sweet, that's a little nicer. Okay, so admittedly that's not anything new. Let's now get it working using the composition API. Just like everything else we've used from the composition API, we'll need to import a utility function.
This time, we need to import computed. Next, we'll define our price pretty function inside the setup function and give it the same logic as before. While we're at it, we can go ahead and remove the options API version. I've chosen to define the function here as an arrow function, just for simplicity's sake.
I like how I can define it all on one line, but there's nothing special about it being defined this way. You're welcome to define it with the more traditional syntax if that's what you're more comfortable with. Now, in order to transform this function into a computed property, all we have to do is call computed on it. Great, we're almost there.
but there's one last thing that needs to change. Can you spot it? That's right. Since we're inside the setup function, we no longer have access to the component instance via the this keyword.
price. Lastly, we'll just return the computed prop from the setup method. Sweet. It all still works as expected.
Also, as with the options API, we can provide both the getter and is setter for our computed properties. Cool. Let's just take that back to being a getter now. value when inside the setup function.
To demonstrate this, we can create a price pretty sentence computed property. All right. That's all there is to working with computed properties in the Composition API. Using computed props with the Composition API, as we have in this lesson, doesn't really demonstrate any clear advantage over using them with the Options API.
The real power, however, comes into play when you extract your logic into composables for reuse in multiple components, or when you have extra complex components that could benefit from organization by logical concern. But, now you'll be ready to use the computed function. whenever one of those situations arise.