数字滚动变化-指令形式

话不多说,直接上代码

<template>
	<div
	  v-data-scroll="{
	    target: 100
	    speed: 1000
	  }"
	>100div> 
template>

<script setup lang="ts">
import { DirectiveBinding } from 'vue';

function dataScroll(el: HTMLElement, binding: DirectiveBinding) {
  // mounted 时,binding.oldValue 为 undefined
  let origin = binding.oldValue?.target || 0;
  let {
    target,
    speed
  } = binding.value;
  // 目标值与原值一样则不进行任何操作
  if (origin === target) return

  // 计算每次改变的值
  let difNumber = (target - origin) / speed * 10;
  // 恢复为原来的值,不恢复的话会闪一下
  el.innerText = origin;

  let timer = setInterval(() => {
    if (origin + difNumber < target) {
      origin += difNumber
    } else {
      origin = target;
      clearInterval(timer);
    }
    el.innerText = origin.toFixed(0);
  }, 10)
}

const VDataScroll =  {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    dataScroll(el, binding)
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    dataScroll(el, binding)
  }
}
script>

你可能感兴趣的:(vue,vue.js,javascript,前端)