Vue Answers

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

    <p>The current time is: {{ currentTime }}</p>
    <p>The current hour is: {{ currentHour }}</p>

export default {
  data() {
    return {
      currentTime: new Date()
  computed: {
    currentHour() {
      return this.currentTime.getHours();
  created() {
    // Update the currentTime property every second
    setInterval(() => {
      this.currentTime = new Date();
    }, 1000);

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *