index.vue 986 Bytes
<template lang="pug">
  span(ref="countUp")
</template>
<script>
import { CountUp } from 'countup.js'

export default {
  name: 'CountUp',
  props: {
    // 目标数字
    end: {
      type: Number,
      default: 0
    },
    // 默认配置
    options: {
      type: Object,
      default: () => {
        return {
          startVal: 0,
          decimalPlaces: 0,
          duration: 1,
          separator: ',',
          decimal: '.'
        }
      }
    }
  },
  data() {
    return {
      numAnim: null
    }
  },
  watch: {
    end: {
      handler(newVal, oldVal) {
        this.numAnim.update(newVal)
      }
    }
  },
  mounted() {
    this.initCountUp()
  },
  beforeDestroy() {
    this.numAnim = null
  },
  methods: {
    initCountUp() {
      this.numAnim = new CountUp(this.$refs.countUp, this.end, this.options)
      if (!this.numAnim.error) {
        this.numAnim.start()
      } else {
        console.error(this.numAnim.error)
      }
    }
  }
}
</script>