为什么我的秒表在刷新时增加固定的时间?
我有一个Vue.js的脚本,它在我刷新页面时会给我的计时器加上额外的6个小时。这个脚本其实就是一个按钮,点击后可以记录时间,停止时会把时间发送到一个Django模型里。我可以正常记录时间,但是每次刷新页面后,我的计时器上总是多出6个小时:
Vue.js脚本:
var NavbarApp = {
data() {
return {
seconds: {{ active_entry_seconds }},
trackingTime: false,
showTrackingModal: false,
timer: null,
entryID: 0,
startTime: '{{ start_time }}'
}
},
delimiters: ['[[', ']]'],
methods: {
startTimer() {
fetch('/apps/api/start_timer/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
}
})
.then((response) => {
return response.json()
})
.then((result) => {
this.startTime = new Date()
this.trackingTime = true
this.timer = setInterval(() => {
this.seconds = (new Date() - this.startTime) / 1000
}, 1000)
})
},
stopTimer() {
fetch('/apps/api/stop_timer/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
}
})
.then((response) => {
return response.json()
})
.then((result) => {
this.entryID = result.entryID
this.showTrackingModal = true
this.trackingTime = false
window.clearTimeout(this.timer)
})
},
discardTimer() {
fetch('/apps/api/discard_timer/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
}
})
.then((response) => {
this.seconds = 0
this.showTrackingModal = false
})
},
addLater() {
this.seconds = 0
this.showTrackingModal = false
},
addToTask() {
console.log('addToTask')
window.location.href = '/apps/track_entry/' + this.entryID + '/'
}
},
mounted() {
if (this.seconds !== 0) {
this.trackingTime = true
this.timer = setInterval(() => {
this.seconds = (new Date() - new Date(this.startTime)) / 1000
}, 1000)
}
},
computed: {
readableSeconds() {
const d = Number(this.seconds);
const h = Math.floor(d / 3600);
const m = Math.floor(d % 3600 / 60);
const s = Math.floor(d % 3600 % 60);
const hDisplay = h > 0 ? h + (h == 1 ? "h, " : "h, ") : "";
const mDisplay = m > 0 ? m + (m == 1 ? "m, " : "m, ") : "";
const sDisplay = s >= 0 ? s + (s == 1 ? "s" : "s") : "";
return hDisplay + mDisplay + sDisplay;
}
}
}
Vue.createApp(NavbarApp).mount('#navbar-app')
HTML:
<div class="col-md-auto mt-md-0 mt-4" id="navbar-app">
<div class="hstack gap-1 flex-wrap">
<div class="navbar-item" v-if="!trackingTime">
<div class="buttons">
<button class="btn btn-success add-btn" @click="startTimer()">
Start Timer
</button>
</div>
</div>
<div class="navbar-item" v-else>
<div class="buttons">
<div class="buttons">
<button class="btn btn-warning add-btn" @click="stopTimer()">
[[ readableSeconds ]] (stop)
</button>
</div>
</div>
</div>
如果我缺少了什么信息或者代码,请告诉我。