2
votes

so in my code, I have a computed value today that allows me to access the current day, month and year, using the following code:

today: function() {
  var currentDate = new Date();
  return {
    day: currentDate.getDate(),
    month: currentDate.getMonth(),
    year: currentDate.getFullYear()
  };
}

Now as far as my understanding goes, the difference between computed properties and methods is that computed props are cached and only recalculated if their dependencies (for example, a normal property) changed, while methods are fully calculated every time.

Now in my case, there are no dependencies. So, if on initialization, it's the 24th Dec 2017, late at night, and I access today.day a few minutes later when it's the 25th - will I be given the original value or will the value be recalculated?

Technically, no properties are dependencies of this computed property, so nothing changed. According to the following extract from the official guide, today.day should still equal 24.

However, the difference is that computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.

1

1 Answers

2
votes

The answer is, in fact, even hidden in a few lines of code in the official guide:

This also means the following computed property will never update, because Date.now() is not a reactive dependency:

computed: {
  now: function () {
    return Date.now()
  }
}

Therefore, in this or similar cases, you should use methods.

I hope this helps others that don't feel like reading the whole guide every time they have a question, and instead prefer to just use google / stackoverflow.