Computed vs. Methods — Vue JS

Jessica Lee
2 min readMay 23, 2021

It has been only a few weeks studying Vue JS and the transition from studying React to Vue was a little bit confusing, because of some of the concepts were new to me. Especially, I wasn’t quite sure about when to use computed or methods. Reading an official document is always helpful, but I personally find it hard to get a clear picture of concepts by reading the document for the first time before trying it myself. So, I feel it is important to do a combination of trying it yourself and reading the document.

computed: {
scaleSize() {
return (this.scaleCount / this.totalCount) * 100;
},
},

Here, scaleCount and totalCount are both props. As I am creating a poll, I need the total counts of users’ participation, and the count for each scale so that I can get the number result. I used computed here for below reasons:

  • I need to create new data from existing data sources
  • I want to reduce complicated and repetitive codes to refer to the data
  • I am not listening to any events happening in the DOM

Using methods instead of computed here would make the same result. However, the difference is that computed properties are cached and they change only when their dependencies (data inside) change. Methods re-evaluate every time they are called. So, it means that using methods instead of computed could unnecessarily run functions. It would not affect too much if it is for a simple task, but it seems to me that considering to use computed where you can (if you need caching) first before using methods can be a good habit to write a more efficient codes.

methods: {
handleChoicesStatus(index) {
if (!this.selectMultiple) {
if (this.choicesStatus[index] === false) {
const newArr = this.choices.map(() => {
return false;
});
newArr[index] = !newArr[index];
this.choicesStatus = newArr;
} else {
this.choicesStatus[index] = !this.choicesStatus[index];
}
...

Here’s an example where I used a method. This handleChoicesStatus(index) is called when a choice from multiple choice question is clicked. I used a method because:

  • I am listening to a click event.
  • The data inside the function needs to change whenever the click event happens.
  • the method has a parameter.

Vue JS recommends to use a method when it needs to accept a parameter. However, note that you can still pass a parameter to computed property by returning an anonymous function with a parameter.

--

--