vue中我们会使用各种倒计时的方法这里就为大家提供一个倒计时的方法,
话不多说代码走起:
<template>
<div>
<button @click="add()">点击开始倒计时</button>
<button @click="chongzhi">重置</button>
<p>{{minute}}:{{second}}</p>
</div>
</template>
<script type="text/ecmascript-6">
export default {
data() {
return {
minutes:15,
seconds:0
}
},
methods: {
num:function (n) {
return n <10 ?'0' + n :'' + n
},
add() {
var _this =this
var 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)
},
chongzhi() {
this.minutes =15
this.seconds =0
},
},
watch: {
second: {
handler(newVal) {
this.num(newVal)
}
},
minute: {
handler(newVal) {
this.num(newVal)
}
}
},
computed: {
second:function () {
return this.num(this.seconds)
},
minute:function () {
return this.num(this.minutes)
}
}
}
</script>
<style></style>