ブログの投稿ログ

2021年
9月
8月
7月
6月

数字のカウントアップアニメーションを実装

hoge

codesandbox

// HellowWorld.vue

<template>
  <div>
    // 出力される数字
    <span>{{ animated_num }}</span>
  </div>
</template>


<script>
export default {
  props: {
    // Appからのvalue
    value: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
     // 出力する値
      animated_num: 0,
    };
  },
  watch: {
    // 入力される前/された後の数字を引数へ定義
    value(newValue, oldValue) {
			// カウンター初期
      let timeCnt = 0;
			// タイマーを定義
      let timer;
      const animate = () => {
				// カウンターを1ずつ追加
        timeCnt++;
				// カウンターが60以上の時
        if (timeCnt <= 60) {
					// 入力された桁数の数字を計算しanimated_numへ代入
          this.animated_num =
            Math.floor(((newValue - oldValue) * timeCnt) / 60) + oldValue;
					// 1/10秒でanimateを実行
          timer = setTimeout(() => {
            animate();
          }, 10);
        } else {
          clearTimeout(timer);
          timer = null;
          this.animated_num = newValue;
        }
      };
      animate();
    },
  },
  mounted() {
    this.animated_num = this.value;
  },
};
</script>

<style scoped>
span {
  padding-top: 30px;
  font-size: 40px;
}
div {
  margin: 30px auto 0;
}
</style>