<template> <em>{{numvalue}} </em> </template> <script> export default { props: ['val'], data () { return { oldvalue: 0, numvalue: 0 } }, methods: { numFun (startNum, maxNum) { var that = this let numText = startNum; let addnum = Math.floor((maxNum - startNum) / 10) //10代表數字變化時最大跳動次數 let golb; // 為了清除requestAnimationFrame function numSlideFun () { // 數字動畫 numText += addnum; // 速度的計算可以為小數 。數字越大,滾動越快 if (numText >= maxNum) { numText = maxNum; cancelAnimationFrame(golb); } else { setTimeout(function () { golb = requestAnimationFrame(numSlideFun); }, 200);//200代表翻牌的頻率 } that.numvalue = numText // console.log(numText) } function subtractlideFun () { // 數字動畫 numText += addnum; // 速度的計算可以為小數 。數字越大,滾動越快 if (maxNum >= numText) { numText = maxNum; cancelAnimationFrame(golb); } else { setTimeout(function () { golb = requestAnimationFrame(subtractlideFun); }, 200); } that.numvalue = numText // console.log(numText) } if (startNum < maxNum) { numSlideFun(); // 遞增數字翻牌 } else { subtractlideFun(); // 遞減數字翻牌 } } }, watch: { val (value) { if (value === undefined) { this.numvalue = 0 this.oldvalue = value } else { if (this.oldvalue === 0) { this.numvalue = value; this.oldvalue = value } else { this.numFun(this.oldvalue, value) this.oldvalue = value } } } } } </script>
最近做大屏展示,因為數字非常大到億以上,要用到數字滾動功能,網上找的都不如意,翻滾的時間久,跳動太快不可控,就自己寫了一個。