我正在尝试为测验创建一个计时器。计时器是从 API 输出中获取的,以秒为单位。我正在使用 Vuex 来存储 API 的结果。并使用 getter 获取 Timer 组件中存储的计时器。一旦我以秒为单位获得计时器值,我将其转换为计算属性内的小时、分钟和秒,然后我尝试将计时器减少 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
值定义属性时会触发观察器一次,然后在为其分配值时触发两次。尝试:
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)
}
}
}
}
关于javascript - Console.log 在 Vue js 观察器中被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60135644/