Javascript 在Vue js watcher中调用Console.log两次

Javascript 在Vue js watcher中调用Console.log两次,javascript,vue.js,vuejs2,vue-component,vuex,Javascript,Vue.js,Vuejs2,Vue Component,Vuex,我正在尝试为测验创建计时器。计时器从API输出中获取,单位为秒。我正在使用Vuex存储API的结果。以及使用getter获取计时器组件中存储的计时器。一旦我以秒为单位获得计时器值,我将其转换为计算属性中的小时、分钟和秒,然后尝试将计时器减少1秒。不知何故,我设法使用watcher属性减少了计时器,但问题是计时器没有减少-1,而是减少了-2。当我在watcher中调用console.log时,我注意到console.log被调用了两次。一次使用未定义的计时器值,一次使用计时器的实际值。我不知道我是

我正在尝试为测验创建计时器。计时器从API输出中获取,单位为秒。我正在使用Vuex存储API的结果。以及使用getter获取计时器组件中存储的计时器。一旦我以秒为单位获得计时器值,我将其转换为计算属性中的小时、分钟和秒,然后尝试将计时器减少1秒。不知何故,我设法使用watcher属性减少了计时器,但问题是计时器没有减少-1,而是减少了-2。当我在watcher中调用console.log时,我注意到console.log被调用了两次。一次使用未定义的计时器值,一次使用计时器的实际值。我不知道我是否用正确的方式做了这件事,因为我是Vuejs的新手。请帮助我解决这个问题,并纠正我的错误。我会附上代码,我试图写到现在

谢谢

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)
      }
    }
  }
})
const Timer=Vue.component('Timer'){
模板:`
{{hour}}:{{min}:{{{sec}
`,
计算:{
…Vuex.mapGetters([
“该走了”
]),
小时{
设h=Math.floor(这次左/3600)
返回h>9?h:'0'+h;
},
min(){
设m=数学楼层(这次左%3600/60);
返回m>9?m:'0'+m
},
第()节{
让s=Math.floor(这次离开%3600%60);
返回s>9?s:'0'+s
}
},
观察:{
剩余时间:{
立即:是的,
处理程序(newVal){
const timer=此时间\左
设置间隔(()=>{
//this.$store.commit('UPDATE\u quick\u TIMER',this.time\u left)
console.log(这次离开)
}, 1000)
}
}
}
})

你没有做错什么。首先使用
undefined
值定义属性时,将触发观察者一次,然后在为其指定值时触发观察者两次。尝试:

 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)
        }
      }
    }
  }