在项目中使用到了倒计时来提醒用户,为了自己和大家以后方便copy,写个小demo。
时 : 分 : 秒
data () {
return {
hour: 6, // 小时
minutes: 2, // 分钟
seconds: 5, // 秒
}
},
mounted () {
this.timer()
},
methods: {
timer () {
let _this = this
// 创建一个定时器
let time = window.setInterval(function () {
// 如果秒数为0 && 分钟数还没有为0
if (_this.seconds === 0 && _this.minutes !== 0) {
// 秒数变为59 分钟数--
_this.seconds = 59
_this.minutes -= 1
// 都为0的时候 清除定时器
} else if (_this.minutes === 0 && _this.seconds === 0 && _this.hour === 0) {
window.clearInterval(time)
// 分钟数和秒数同时为0 小时数-- 分钟数和秒数都变为59
} else if (_this.minutes === 0 && _this.seconds === 0) {
_this.seconds = 59
_this.minutes = 59
_this.hour -= 1
} else {
_this.seconds -= 1
}
}, 1000)
}
}
分 : 秒
想要实现 00 : 00的样式 可以使用插值表达式再使用三目运算来判断
let time = window.setInterval(function () {
if (_this.seconds === 0 && _this.minutes !== 0) {
_this.seconds = 59
_this.minutes -= 1
} else if (_this.minutes === 0 && _this.seconds === 0) {
_this.seconds = 0
window.clearInterval(time)
} else {
_this.seconds -= 1
}
}, 1000)