简体   繁体   中英

Console.log getting called twice in Vue js watcher

I am trying to create a timer for quiz. The timer is obtained from the API output which is in seconds. I am using Vuex to store result of the API. And the using getters to get the stored timer in the Timer component. Once I get the timer value in seconds I convert it into hrs, min and sec inside a computed property and then I try to reduce the timer by 1 second. Somehow I managed to reduce the timer using watcher property, but the issue is that the timer is not reducing by -1, it is reduced by -2. When I console.log inside the watcher I noticed that the console.log is getting called twice. Once with an undefined value of timer and once with an actual value of timer. I don't know If i am doing it in the right way or not as I am a newbie in Vuejs. Please help me resolve this issue and also correct me where I am wrong. I will attach the code which i tried writing up till now.

Thanks.

const Timer = Vue.component('Timer', {
  template: `
    <div class="navbar-nav ml-auto" v-if="time_left">
     {{hour}} : {{min}} : {{sec}}
    </div>
  `,
  computed: {
    ...Vuex.mapGetters([
        'time_left'
      ]),
    hour(){
      let h = Math.floor(this.time_left / 3600)
      return h > 9 ? h : '0' + h;
    },
    min(){
      let m = Math.floor(this.time_left % 3600 / 60);
      return m > 9 ? m :'0' + m
    },
    sec(){
      let s = Math.floor(this.time_left % 3600 % 60);
      return s > 9 ? s : '0' + s
    }
  },
  watch: {
    time_left: {
      immediate: true,
      handler (newVal) {
        const timer = this.time_left
        setInterval(() => {
          // this.$store.commit('UPDATE_QUIZ_TIMER', this.time_left)
          console.log(this.time_left)
        }, 1000)
      }
    }
  }
})

You' re not doing anything wrong. The watcher is fired once when the property is first defined with undefined value and then is fired twice when a value is assigned to it. Try:

 watch: {
    time_left: {
      immediate: true,
      handler (newVal) {
        if(newVal !== undefined){
          const timer = this.time_left
          setInterval(() => {
            // this.$store.commit('UPDATE_QUIZ_TIMER', this.time_left)
            console.log(this.time_left)
          }, 1000)
        }
      }
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM