- 需求:实现数字动画,并实现数字千位分隔符格式(8888,显示为8,888),数字从0-8888实现动画递增
- utils/common.js
export function numAnimation(current, target, _this, property, step = 1, totalTime = 1000, duration = 20, timer = '') {
clearInterval(timer)
let ternialStep = 0
if (target >= current) {
ternialStep = (target - current) / (totalTime / duration)
} else {
ternialStep = (current - target) / (totalTime / duration)
}
if (ternialStep > 10) {
ternialStep = parseInt(ternialStep).toString().split('')
ternialStep[ternialStep.length - 1] = 1
ternialStep = parseInt(ternialStep.join(''))
} else {
ternialStep = Math.ceil(ternialStep) || 1
}
if (current < target) {
timer = setInterval(() => {
if (step === 0.1) {
_this[property] = (_this[property] * 1000 + (step + ternialStep) * 1000) / 1000
} else if (step === 0.01) {
_this[property] = (_this[property] * 1000 + (step + ternialStep) * 1000) / 1000
} else {
_this[property] = _this[property] + ternialStep
}
if (_this[property] >= target) {
_this[property] = target
clearInterval(timer)
}
}, duration)
} else if (current > target) {
timer = setInterval(() => {
if (step === 0.1) {
_this[property] = (_this[property] * 1000 - (step + ternialStep) * 1000) / 1000
} else if (step === 0.01) {
_this[property] = (_this[property] * 1000 - (step + ternialStep) * 1000) / 1000
} else {
_this[property] = _this[property] - ternialStep
}
if (_this[property] <= target) {
_this[property] = target
clearInterval(timer)
}
}, duration)
}
}
export const numberFilter = function (value, cut = 2) {
if (parseFloat(value).toString() == 'NaN') return '0.00'
let num = value.toString().split('.')
let zs = num[0]
let xs = num[1]
const intPartFormat = zs.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
if (xs != null) {
if (cut == 0) {
return intPartFormat + '.' + xs
} else if (cut == -1) {
return intPartFormat
} else {
return intPartFormat + '.' + xs.substr(0, cut)
}
} else {
return intPartFormat
}
}
<div class="user-number">{{ totalUser | numberFilter }}</div>
<div class="zoom-number">
<div class="zoom-number-item" v-for="(item, index) in zommDataList" :key="index">
<span>{{ item.name }}</span>
<span>{{ item.value | numberFilter }}</span>
</div>
</div>
import { numAnimation, numberFilter } from '@/utils/common'
data() {
return {
totalUser: 0,
zommDataList: [
{ name: '总数', value: 0 },
{ name: '占用', value: 0 },
],
}
},
filters: {
numberFilter,
},
numAnimation(this.totalUser, res.data.userTotalCount || 0, this, 'totalUser')
numAnimation(this.zommDataList[0].value, res.data.total || 0, this.zommDataList[0], 'value')
numAnimation(this.zommDataList[1].value, res.data.used || 0, this.zommDataList[1], 'value')
|