gpt4 book ai didi

javascript - 使用 Vue 增加格式化计时器

转载 作者:行者123 更新时间:2023-11-30 14:52:10 24 4
gpt4 key购买 nike

我正在构建一个基本的 Timer Vue 组件。计时器以秒为单位递增,用户可以在单击时播放和暂停计时器。这是组件:

<template>
<div v-bind:class="{workspaceTimer: isRunning}">
<a class="u-link-white" href="#" @click="toggleTimer">
{{ time }}
<span v-if="isRunning">
Pause
</span>
<span v-else>
Play
</span>
</a>
</div>
</template>

<script>
export default {
props: ['order'],
data() {
return {
time: this.order.time_to_complete,
isRunning: false,
interval: null,
}
},
watch: {
time: function (newTime) {
this.saveTime()
}
},
methods: {
toggleTimer() {
if (this.isRunning) {
clearInterval(this.interval);
} else {
this.interval = setInterval(this.incrementTime, 1000);
}
this.isRunning = !this.isRunning;
},
incrementTime() {
this.time = parseInt(this.time) + 1;
},
formattedTime() {
var sec_integer = parseInt(this.time, 10);
var hours = Math.floor(sec_integer / 3600);
var minutes = Math.floor((sec_integer - (hours * 3600)) / 60);
var seconds = sec_integer - (hours * 3600) - (minutes * 60);

if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
this.time = +minutes+':'+seconds;
},
saveTime: _.debounce(
function () {
var self = this;
axios.put(location.pathname, {time_to_complete: self.time})
.then(function (response) {
console.log('timer: ' + response.data.time_to_complete);
})
.catch(function (error) {
console.log('Error: ' + error);
})
},
1000
)

}
</script>

我将第二个计数描述为整数,但想将第二个计数显示为 mm:ss,并使该格式化值递增,例如00:59 递增到 1:00。

我可以使用方法或计算属性轻松格式化我的第二个值(请参阅该示例中的 formattedTime() 方法),但我不确定如何递增该字符串,然后格式化增加的字符串。我是否需要观察该字符串的变化,然后格式化更新后的字符串?

最佳答案

解决了。答案实际上是在我的组件中使用本地过滤器:

filters: {
formattedTime: function (value) {
var sec_num = parseInt(value, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);

//if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return +minutes+':'+seconds;
}
},

然后将该过滤器应用于我的时间变量:{{ time |格式化时间 }}.

关于javascript - 使用 Vue 增加格式化计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47947163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com