gui-number-animate.vue 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <template>
  2. <text :style="{
  3. fontSize:fontSize,
  4. fontWeight:fontWeight,
  5. color:color,
  6. lineHeight:lineHeight
  7. }">{{numAnimate}}</text>
  8. </template>
  9. <script>
  10. export default{
  11. name : "gui-number-animate",
  12. props : {
  13. num : { type : Number, default : 0},
  14. stepNumber : { type : Number, default : 50 },
  15. timer : { type : Number, default : 1000 },
  16. keepInt : { type : Boolean, default : false },
  17. fontSize : { type : String, default : '28rpx' },
  18. color : { type : String, default : '#333333' },
  19. lineHeight : { type : String, default : '50rpx' },
  20. fontWeight : { type : String, default : '400' }
  21. },
  22. data() {
  23. return {
  24. numAnimate : 0,
  25. intervalId : null
  26. }
  27. },
  28. created:function(){
  29. if(this.num != 0){this.run();}
  30. },
  31. watch:{
  32. num : function(val){
  33. if(this.intervalId != null){clearInterval(this.intervalId);}
  34. this.run();
  35. }
  36. },
  37. methods:{
  38. run : function(){
  39. let timer = this.timer / this.stepNumber;
  40. let step = Math.floor((this.num / this.stepNumber) * 100) / 100;
  41. this.intervalId = setInterval(() => {
  42. // 正值
  43. if(this.num >= 0){
  44. if(this.numAnimate >= this.num){
  45. this.numAnimate = this.num;
  46. clearInterval(this.intervalId);
  47. this.$emit('done');
  48. return;
  49. }
  50. }else{
  51. if(this.numAnimate <= this.num){
  52. this.numAnimate = this.num;
  53. clearInterval(this.intervalId);
  54. this.$emit('done');
  55. return;
  56. }
  57. }
  58. let res = this.numAnimate + step;
  59. this.numAnimate = this.keepInt ? parseInt(res) : Math.floor(res * 100) / 100;
  60. }, timer);
  61. }
  62. }
  63. }
  64. </script>
  65. <style scoped>
  66. </style>