[英]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.
计时器是从 API 输出中获得的,以秒为单位。 I am using Vuex to store result of the API.
我正在使用 Vuex 来存储 API 的结果。 And the using getters to get the stored timer in the Timer component.
并使用 getter 来获取 Timer 组件中存储的计时器。 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.
一旦我以秒为单位获得计时器值,我将它转换为计算属性中的 hrs、min 和 sec,然后我尝试将计时器减少 1 秒。 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.
不知何故,我设法使用 watcher 属性减少了计时器,但问题是计时器没有减少 -1,而是减少了 -2。 When I console.log inside the watcher I noticed that the console.log is getting called twice.
当我在观察者中使用 console.log 时,我注意到 console.log 被调用了两次。 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.
我不知道我是否以正确的方式做这件事,因为我是 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.当属性第一次被定义为
undefined
值时,watcher 被触发一次,然后当一个值被分配给它时被触发两次。 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)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.