![](/img/trans.png)
[英]Why is `Promise.then` called twice in a React component but not the console.log?
[英]Console.log getting called twice in Vue js watcher
我正在尝试为测验创建一个计时器。 计时器是从 API 输出中获得的,以秒为单位。 我正在使用 Vuex 来存储 API 的结果。 并使用 getter 来获取 Timer 组件中存储的计时器。 一旦我以秒为单位获得计时器值,我将它转换为计算属性中的 hrs、min 和 sec,然后我尝试将计时器减少 1 秒。 不知何故,我设法使用 watcher 属性减少了计时器,但问题是计时器没有减少 -1,而是减少了 -2。 当我在观察者中使用 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)
}
}
}
})
你没有做错任何事。 当属性第一次被定义为undefined
值时,watcher 被触发一次,然后当一个值被分配给它时被触发两次。 尝试:
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.