How to make computed Vue properties dependent on current time?

Spread the love

To make a computed property in Vue.js dependent on the current time, you can utilize a combination of JavaScript’s Date object and Vue’s reactivity system.


For example, we write

In this example, we have a computed property currentHour that depends on the currentTime data property.
We initialize currentTime with the current date and time.
We update currentTime every second using setInterval to ensure that the computed property is re-evaluated as time progresses.
With this setup, currentHour will automatically update every second to reflect the current hour based on the system time.
We can similarly create computed properties dependent on other time-related aspects such as minutes, seconds, etc., by accessing different methods of the Date object.