Open klren0312 opened 5 years ago
<template>
<div class="number">{{ calcValue }}</div>
</template>
<script>
export default {
name: 'NumRun',
props: {
value: {
type: Number
},
start: {
type: Boolean,
default: false
}
},
data() {
return {
calcValue: 0,
isFinish: false,
timer: null
}
},
mounted() {
if (this.start && this.value !== this.calcValue) {
this.run()
}
},
beforeDestroy() {
this.calcValue = this.value
},
deactivated() {
this.calcValue = this.value
},
methods: {
add() {
if (this.calcValue >= this.value) {
this.calcValue = this.value
this.isFinish = true
} else {
this.calcValue += 1
}
},
run() {
const tick = () => {
this.add()
this.timer = requestAnimationFrame(this.run)
if (this.isFinish) {
this.timer && cancelAnimationFrame(this.timer)
this.timer = null
}
}
tick()
}
},
watch: {
start(nv) {
if (nv && this.value !== this.calcValue) {
this.run()
}
}
}
}
</script>
<style lang=""></style>