【Vue】vue3中通过自定义指令实现数字的动态增加动画

在Vue 3中通过自定义指令实现数字的动态增加动画,可以利用Vue的自定义指令功能,这允许你扩展Vue的内置指令,使得DOM操作更加灵活和强大。以下是如何创建一个自定义指令来实现数字动态增加动画的步骤:

效果演示

代码实现

1、定义指令代码

ts 复制代码
import { Directive } from 'vue';

// 动画持续时间,ms
const DURATION = 1500;

/**
 * @description 基于Vue3自定义指令,实现数字递增动画效果
 *
 * @example     `<div v-increase="100"></div>`
 */
export const increase: Directive = {
  // 在绑定元素的父组件
  // 及他自己的所有子节点都挂载完成后调用
  mounted(el, binding) {
    const { value: maxCount } = binding;

    el.$animation = animate((progress) => {
      el.innerText = Math.floor(maxCount * progress);
    }, DURATION);
  },
  // 绑定元素的父组件卸载后调用
  unmounted(el) {
    el.$animation.cancel();
  },
};

/**
 * @description             基于requestAnimationFrame,实现在持续时间内执行动画的方法
 *
 * @param fn                动画执行函数,参数progress表示完成的进度
 * @param duration          动画持续时间
 * @returns {object.cancel} 取消动画
 */
export const animate = function (fn: (progress: number) => void, duration: number) {
  const animate = () => {
    animation = requestAnimationFrame(animate);

    const now = new Date().getTime();
    const progress = Math.floor(((now - START) / duration) * 100) / 100;
    fn(progress > 1 ? 1 : progress);
    // 到达持续时间,结束动画
    if (now - START > duration) {
      cancel();
    }
  };

  const cancel = () => {
    cancelAnimationFrame(animation);
  };

  const START = new Date().getTime();

  let animation = requestAnimationFrame(animate);
  return {
    cancel: () => {
      cancelAnimationFrame(animation);
    },
  };
};

2、注册自定义指令

ts 复制代码
import { type App } from 'vue';
import { increase } from './increase';

/** 挂载自定义指令 */
export function loadDirectives(app: App) {
  app.directive('increase', increase);
}

3、加载自定义指令

main.ts

ts 复制代码
import { loadDirectives } from '@/directives';

/** 加载自定义指令 */
loadDirectives(app);

参考资料

自定义指令 | Vue.js
基于Vue3自定义指令,实现数字递增动画效果的v-increase

相关推荐
Vicky&James2 分钟前
WPF到Web的无缝过渡:英雄联盟客户端项目OpenSilver迁移实战
前端·wpf
m0_748233645 分钟前
RabbitMQ 进阶
android·前端·后端
不想有bug的小菜鸟14 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_7482386315 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u01005596016 分钟前
前端代理,解决跨域问题讲解
前端
quitv21 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238129 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星31 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一粒沙-1 小时前
iOS 将GIF图分享至微信
前端·ios
graywen1 小时前
从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
前端