【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

相关推荐
蓝婷儿19 分钟前
前端面试每日三题 - Day 34
前端·面试·职场和发展
CopyLower21 分钟前
苹果计划将AI搜索集成至Safari:谷歌搜索下降引发的市场变革
前端·人工智能·safari
我是Superman丶2 小时前
【技巧】前端VUE用中文方法名调用没效果的问题
前端·javascript·vue.js
斯~内克2 小时前
Vue 3 中 watch 的使用与深入理解
前端·javascript·vue.js
蜡笔小柯南4 小时前
解决:npm install报错,reason: certificate has expired
前端·npm·node.js
lqj_本人5 小时前
鸿蒙OS&UniApp制作多选框与单选框组件#三方框架 #Uniapp
前端·javascript·uni-app
@PHARAOH6 小时前
WHAT - 前端开发流程 SOP(标准操作流程)参考
前端·领导力
松树戈7 小时前
plus-ui&RuoYi-Vue-Plus 基于pgSql本地运行实践
前端·vue.js·spring boot·ui
new6669997 小时前
css画图形
前端·css
Yvonne爱编码8 小时前
CSS- 1.1 css选择器
前端·css·状态模式·html5·hbuilder