<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数字加载</title>
<style>
[v-cloak]{
display: none;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<div>{{num1}}</div>
<div>{{num2}}</div>
<div>{{num3}}</div>
<button @click="getData">加载</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script>
new Vue({
el: '#app',
data: {
num1: 0, // 加载中的值
num2: 0,
num3: 0,
s: null, // Set数据
},
created() {
this.s = new Set()
this.getData()
},
methods: {
numberLoading(newNum, oldNum, name) {
if (newNum === oldNum) return
const gap = Math.abs(newNum - oldNum)
const step = Math.ceil(gap / 16)
let timer = setInterval(() => {
if (newNum > oldNum) {
this[name] += step
if (this[name] > newNum) {
this[name] = newNum
clearInterval(timer)
}
} else {
this[name] -= step
if (this[name] < newNum) {
this[name] = newNum
clearInterval(timer)
}
}
}, 16)
// 把定时器存放set数据中,防止上次定时器执行未完成,及时清除
this.s.add(timer)
},
getData() {
setTimeout(() => {
const num1 = Math.floor(Math.random()*100000)
const num2 = Math.floor(Math.random()*1000)
const num3 = Math.floor(Math.random()*30)
console.log(num1, num2, num3);
// 把定时器存放set数据中,防止上次定时器执行未完成,及时清除
for(const key of this.s) {
clearInterval(key)
}
this.s.clear()
this.numberLoading(num1, this.num1, 'num1')
this.numberLoading(num2, this.num2, 'num2')
this.numberLoading(num3, this.num3, 'num3')
}, 300)
}
}
})
</script>
</body>
</html>
数字加载效果
于 2024-01-13 09:39:12 首次发布