I've written a small clock component for one of my projects, but I didn't get the value for my clock refreshed.
A short extract of my code:
    time() {
      let now = new Date();
      let hour = this.zeroPadding(now.getHours());
      let minute = this.zeroPadding(now.getMinutes());
      let second = this.zeroPadding(now.getSeconds());
      console.log(hour.toString() + minute.toString() + second.toString())
      if(!this.realtime)
        return this.value
      else
        return hour.toString() + ":" + minute.toString() + ":" + second.toString()
    }
  },
  mounted() {
    setInterval(() => {
        this.time()
    }, 1000)
  },
  beforeDestroy () {
    clearInterval(this.polling)
  }
Does anyone finde the mistake? Did I understand the polling wrong?
Greetings, Matthias
The time value that you want to display needs to be a data / computed property so that it's reactive and Vue can track it. Concise way to do it:
export default {
  data() {
    return {
      interval: null,
      time: null
    }
  },
  beforeDestroy() {
    // prevent memory leak
    clearInterval(this.interval)
  },
  created() {
    // update the time every second
    this.interval = setInterval(() => {
      // Concise way to format time according to system locale.
      // In my case this returns "3:48:00 am"
      this.time = Intl.DateTimeFormat(navigator.language, {
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
      }).format()
    }, 1000)
  }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With