继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

基于Vue实现的数字滚动组件

lmwang
关注TA
已关注
手记 5
粉丝 3
获赞 5

参数

startVal: 0,		// 起始值
endVal: 10,		// 最终值
speed: 500,		// 速度
decimals: 3,		// 保留几位小数(不会四舍五入)
isReverse: false		// 是否允许从大到小(默认false)

功能代码(可直接复制使用)

<template>
  <span>{{printVal}}</span>
</template>

<script>
export default {
  props: {
    startVal: {
      type: [String, Number],
      default: ''
    },
    endVal: {
      type: [String, Number],
      default: ''
    },
    speed: {
      type: [String, Number],
      default: 5
    },
    decimals: {
      type: [String, Number],
      default: 0
    },
    isReverse: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      start: +this.startVal,
      end: +this.endVal,
      formatSpeed: +this.speed || 5
    };
  },
  computed: {
    formatDecimals() {
      // 是否整数
      let formatDecimals = this.decimals > 0 ? this.decimals : 0;
      return formatDecimals
    },
    decimalsLen() {
      // 1 = 0.001 * decimalsLen(x);
      let decimalsLen = Math.pow(10, this.formatDecimals);
      return decimalsLen;
    },
    printVal() {
      // 保留几位小数
      let start = (
        parseInt(this.start * this.decimalsLen) / this.decimalsLen
      ).toFixed(this.formatDecimals);
      return start;
    }
  },
  watch: {},
  methods: {
    accumulativeMachine() {
      setTimeout(() => {
        if (this.isReverse) {
          let decimals = this.formatDecimals === 0 ? 0 : 1 / this.decimalsLen;
          let formatSpeed = this.formatSpeed / this.decimalsLen + decimals;
          this.start -= formatSpeed;
          if (this.printVal <= this.end) {
            this.start = this.end;
            return
          }
        } else {
          let decimals = this.formatDecimals === 0 ? 0 : 1 / this.decimalsLen;
          let formatSpeed = this.formatSpeed / this.decimalsLen + decimals;
          this.start += formatSpeed;
          if (this.printVal >= this.end) {
            this.start = this.end;
            return
          }
        }
        this.accumulativeMachine();
      }, 8);
    }
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.accumulativeMachine();
    });
  }
};
</script>

<style scoped></style>

用法示例

<count-in :startVal='0' :endVal='100.525' :speed='800' :decimals="3" :isReverse=false />

我是底部
一些开发过程中的经验总结,如果对你有帮助,那真是一件很棒的事,如果内容有什么问题或建议,欢迎在下方留言。😀 😀 😀

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP

热门评论

不同的值使它的滚动速度能不能统一啊

不行啊 跑了两次就不动了 怎么刷新都没用 

123

查看全部评论