<template>
  <span>
    <slot :num="num.toFixed(props.fixed)">{{ num.toFixed(props.fixed) }}</slot>
  </span>
</template>
<script setup>
import { ref, watch, computed, onMounted } from "vue";
const props = defineProps({
  from: {
    type: Number,
    default: 0,
  },
  to: {
    type: [Number],
    default: 0,
  },
  fixed: {
    type: Number,
    default: 0,
  },
  time: {
    type: Number,
    default: 1500,
  },
});
const emits = defineEmits(['end'])
const num = ref(0);
onMounted(() => {
  num.value = props.from;
  change();
});

const change = () => {
  if (num.value.toFixed(props.fixed) == props.to.toFixed(props.fixed)) {
    return;
  }
  play();
};
watch(()=>props.to, change);
let timer = null;
const play = () => {
  if (timer) {
    return;
  }
  let time = 0;
  let step = (props.to - num.value) / (props.time / 100);
  timer = setInterval(() => {
    time += 100;
    if (time >= props.time) {
      num.value = props.to;
      emits('end')
      clearInterval(timer);
      timer = undefined;
      return;
    }
    num.value += step;
  }, 100);
};
</script>