使用momentjs在vuejs中创建倒计时



我有一个以HH:mm:ss格式返回剩余时间的mixin。

Vue.mixin({
methods: {
remainingTime(){
// some calculations based on current time and given time
return timeLeft.toString();
}
....

在组件中,我调用mixin来获取时间

export default {
....
data() {
return {
timeLeft: this.remainingTime(),
....

在我的模板中,我称之为{{timeLeft}},它返回类似01:20:33的东西,但我想将这个值显示为倒计时。因此,当它加载到页面上时,开始倒计时1秒。

我试着使用观察程序,但它不起作用:

watch: {
timeLeft: {
handler(value) {
if (value) {
setInterval(() => {
this.timeLeft;
}, 1000);
}
},
immediate: true,
},
},

用数值保持时间。具有字符串值的当前时间。观察者的工作是注意数字时间的变化并将其转换为字符串。

setInterval((绝对不是观察者的工作。你最终会随意地开始新的定时器。

Vue.config.productionTip = false;
Vue.config.devtools = false;
var app = new Vue({
el: '#app',
data: {
timeLeft: 0,
timeLeftString: '',
timer: null
},
watch: {
timeLeft: function (val) {
const timeZero = moment("1900-01-01 00:00:00");
this.timeLeftString = timeZero.add(val, 'seconds').format("HH:mm:ss")
},
},
mounted() {
this.timeLeft = 63;
this.timer = setInterval(() => {
if (this.timeLeft <= 0) {
clearInterval(this.timer);
alert('Done');
} else {
this.timeLeft--
}
}, 1000)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h1>
{{ timeLeftString }}
</h1>
</div>

如果没有momentjs:您可以使用mod(%(提取小时、分钟和日期。代码取自本文底部的文章。在mounted上运行setInterval,或者每当您获得截止日期-时间的数据时


let countDownDate = new Date("Jan 01, 2023 00:00:00").getTime(); // The deadline
let x = setInterval(() => {
let now = new Date().getTime();
let distance = countDownDate - now;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s"); // Countdown output

if (distance < 0) {
clearInterval(x);
console.log("Too late!") // Text at the end of the countdown
}
}, 1000)

你可以在这里查看https://beetrootacademy.se/blog/front-end-development/js-countdown-timer-14-lines

最新更新