How to use computed properties in Vue

The examples in Vue’s docs aren’t practical. So here are some real-life examples of how to write and use computed properties in Vue.

Sunil Sandhu
Nov 15, 2018 · 5 min read
Image for post
Image for post

There are multiple ways in Vue to set values for the view. This includes directly binding data value to the view, using simple expressions or using filters to do simple transformations on the content. In addition to these, we can also use computed properties to obtain values based on items inside of the data model.

Computed properties in Vue are incredibly useful. So much so that unless you are looking to trigger a function after an event, such as a click event, you should probably analyse whether your function can sit inside of the computed property before looking at the methods property. The reason being that the calculations made inside of computed properties are cached and will only update when needed.

So now that we have given you a quick overview of what computed properties are and why they are useful, it is best that we now delve into some examples so that you can get a better idea of how to use them. When I initially started learning how to use Vue, I read through the documentation on their site. I found that, while it was great that they covered a lot of topics, they didn’t go into many of them in great detail. I gripe I had in particular was that the examples they gave were often really simple and had very little use — such as how to reverse a string. So let’s fix that by going through three real-life use cases for Vue computed properties!

Vue example 1: Using map() and reduce() to obtain the total from a shopping cart

So the first example we will tackle is likely the most complex of the three that we will be tackling today. So let’s get the hard stuff out of the way, because it’s also likely to be the most useful for you!

In our example, we have an eCommerce site. We will be storing all of our items inside of an item array which sits inside of our data() function (this is all fairly standard practice when using Vue components). When we add items to our shopping cart, we need to be able to add the entire item object into our cart. So an example item that gets added into our cart would look like this:

Now considering that this example is focused around simply getting the total price, we could have just added the price from this item object. But in reality, that wouldn’t be very useful, because our shopping cart wouldn’t actually know what items have been added.

So what we want to happen here is that every time an item gets added to the shopping cart, we want Vue to programmatically figure out the total price. This is where our computed properties come into play!

Let’s check our example code, then we’ll explain what is going on:

So we first run the map() function on our cart array which returns a new array that just has the prices of each item. We then immediately call the reduce() function which adds all of the values together and returns the total value.

But how does Vue know to run this every time an item gets added or removed from the cart?

Well, in our example, whenever an item gets added to the cart (by clicking on a button next to each item that says ‘Add To Cart’, the button has a click event attached to it which fires a function called updateCart(), which looks like this:

As you can see, it first pushes an item into our cart. It then calls for the to be assigned the value of the shoppingCartTotal function, which sits inside of our computed properties section! How cool is that?!

Vue example 2: Concatenating strings of data together

Now this example, along with the third example are going to be a little more traditional, and more in line with how you would typically see computed properties being used. Let’s take an example where we have a database full of users and all of this is being loaded into our data() function. Our data structure has a name_first and a name_last value and we want to find an efficient way to concatenate these two together and show it on our page. To make it easier to visualise, this is what our user object could look like:

We can then use a template/string literal to join name_first and name_last together inside of our computed function as such:

Then, inside of our view, we can refer to fullName just like we would with any other value inside of our data():

Which would return Sunil Sandhu!

Vue example 3: Calculating numbers together

So in our final example, we will use v-model to automatically update values in our data() object and then use a computed property to add those two numbers together.

So to begin with, let’s look at our data() object:

Super simple and straight forward. We attach 0 to num1 and num2 from the beginning in order to avoid any issues with null, undefined and NaN.

We then have two input fields in our view:

You can see that we attach v-model onto both with the value for num1 and num2. So whenever we change the value in either of the input fields, those numbers will also update inside of our data() object.

Inside of our computed section, we then have this function:

Which simply adds the two numbers together.

Finally, in our view, we output the value of our answer() function like so:

Super simple and we could easily improve upon this by adding some buttons that trigger add, subtract, multiply and divide.

And there we have it! 🎉

We’ve managed to go through three different, but real-life useable examples of how computed properties can be used in Vue to efficiently take care of updating data. Now that you know how to use computed properties, go and build lots of cool things! Be sure to share, comment and like this post and let me know what awesome things you have been building in Vue!

JavaScript In Plain English

New articles every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store