Home > other >  "now" is not defined when trying to update time
"now" is not defined when trying to update time

Time:09-13

So I am doing a vue.js project and I am trying to have the time update every second. I have initialized the time in data(), then created a function which should update it, and then called the function in mounted() to refresh every second. Problem is that when I call updateTime() it keeps telling me that 'now' is not defined. Why is that?

    <script>
import { createDOMCompilerError } from "@vue/compiler-dom";

export default {
  data() {
    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();

    return {
      now,
      hours,
      minutes,
      seconds,
    };
  },
  methods: {
    updateTime() {
      this.now = new Date();
      this.hours = now.getHours();
      this.minutes = now.getMinutes();
      this.seconds = now.getSeconds();
    },
  },
  mounted() {
    setInterval(() => {
      this.updateTime();
    }, 1000);
  },
  unmounted() {
    clearInterval();
  },
};
</script>

CodePudding user response:

You need to use this.now when assigning to this.hours etc

this.now = new Date();
this.hours = this.now.getHours();
this.minutes = this.now.getMinutes();
this.seconds = this.now.getSeconds();

Also note that clearInterval requires an interval ID to be passed in, which will be returned when you run setInterval

https://developer.mozilla.org/en-US/docs/Web/API/clearInterval

  • Related