vue3 | 数据可视化实现数字滚动特效

news2025/7/17 6:57:24

前言

vue3不支持vue-count-to插件,无法使用vue-count-to实现数字动效,数字自动分割,vue-count-to主要针对vue2使用,vue3按照会报错:
TypeError: Cannot read properties of undefined (reading '_c')
的错误信息。这个时候我们只能自己封装一个CountTo组件实现数字动效。先来看效果图:
请添加图片描述

思路

使用Vue.component定义公共组件,使用window.requestAnimationFrame(首选,次选setTimeout)来循环数字动画,window.cancelAnimationFrame取消数字动画效果,封装一个requestAnimationFrame.js公共文件,CountTo.vue组件,入口导出文件index.js。

文件目录

文件目录

使用示例

<CountTo
 :start="0" // 从数字多少开始
 :end="endCount" // 到数字多少结束
 :autoPlay="true" // 自动播放
 :duration="3000" // 过渡时间
 prefix="¥"   // 前缀符号
 suffix="rmb" // 后缀符号
 />

入口文件index.js


const UILib = {
  install(Vue) {
    Vue.component('CountTo', CountTo)
  }
}

export default UILib

main.js使用

import CountTo from './components/count-to/index';
app.use(CountTo)

requestAnimationFrame.js思路

  1. 先判断是不是浏览器还是其他环境
  2. 如果是浏览器判断浏览器内核类型
  3. 如果浏览器不支持requestAnimationFrame,cancelAnimationFrame方法,改写setTimeout定时器
  4. 导出两个方法 requestAnimationFrame, cancelAnimationFrame
各个浏览器前缀:let prefixes =  'webkit moz ms o';
判断是不是浏览器:let isServe = typeof window == 'undefined';
增加各个浏览器前缀:  
let prefix;
let requestAnimationFrame;
let cancelAnimationFrame;
// 通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式
    for (let i = 0; i < prefixes.length; i++) {
        if (requestAnimationFrame && cancelAnimationFrame) { break }
        prefix = prefixes[i]
        requestAnimationFrame = requestAnimationFrame || window[prefix + 'RequestAnimationFrame']
        cancelAnimationFrame = cancelAnimationFrame || window[prefix + 'CancelAnimationFrame'] || window[prefix + 'CancelRequestAnimationFrame']
    }
    
  //不支持使用setTimeout方式替换:模拟60帧的效果
  // 如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
    if (!requestAnimationFrame || !cancelAnimationFrame) {
        requestAnimationFrame = function (callback) {
            const currTime = new Date().getTime()
            // 为了使setTimteout的尽可能的接近每秒60帧的效果
            const timeToCall = Math.max(0, 16 - (currTime - lastTime))
            const id = window.setTimeout(() => {
                callback(currTime + timeToCall)
            }, timeToCall)
            lastTime = currTime + timeToCall
            return id
        }

        cancelAnimationFrame = function (id) {
            window.clearTimeout(id)
        }
    }

完整代码:

requestAnimationFrame.js

let lastTime = 0
const prefixes = 'webkit moz ms o'.split(' ') // 各浏览器前缀

let requestAnimationFrame
let cancelAnimationFrame

// 判断是否是服务器环境
const isServer = typeof window === 'undefined'
if (isServer) {
    requestAnimationFrame = function () {
        return
    }
    cancelAnimationFrame = function () {
        return
    }
} else {
    requestAnimationFrame = window.requestAnimationFrame
    cancelAnimationFrame = window.cancelAnimationFrame
    let prefix
    // 通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式
    for (let i = 0; i < prefixes.length; i++) {
        if (requestAnimationFrame && cancelAnimationFrame) { break }
        prefix = prefixes[i]
        requestAnimationFrame = requestAnimationFrame || window[prefix + 'RequestAnimationFrame']
        cancelAnimationFrame = cancelAnimationFrame || window[prefix + 'CancelAnimationFrame'] || window[prefix + 'CancelRequestAnimationFrame']
    }

    // 如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
    if (!requestAnimationFrame || !cancelAnimationFrame) {
        requestAnimationFrame = function (callback) {
            const currTime = new Date().getTime()
            // 为了使setTimteout的尽可能的接近每秒60帧的效果
            const timeToCall = Math.max(0, 16 - (currTime - lastTime))
            const id = window.setTimeout(() => {
                callback(currTime + timeToCall)
            }, timeToCall)
            lastTime = currTime + timeToCall
            return id
        }

        cancelAnimationFrame = function (id) {
            window.clearTimeout(id)
        }
    }
}

export { requestAnimationFrame, cancelAnimationFrame }

CountTo.vue组件思路

首先引入requestAnimationFrame.js,使用requestAnimationFrame方法接受count函数,还需要格式化数字,进行正则表达式转换,返回我们想要的数据格式。

引入 import { requestAnimationFrame, cancelAnimationFrame } from './requestAnimationFrame.js'

需要接受的参数:

const props = defineProps({
  start: {
    type: Number,
    required: false,
    default: 0
  },
  end: {
    type: Number,
    required: false,
    default: 0
  },
  duration: {
    type: Number,
    required: false,
    default: 5000
  },
  autoPlay: {
    type: Boolean,
    required: false,
    default: true
  },
  decimals: {
    type: Number,
    required: false,
    default: 0,
    validator (value) {
      return value >= 0
    }
  },
  decimal: {
    type: String,
    required: false,
    default: '.'
  },
  separator: {
    type: String,
    required: false,
    default: ','
  },
  prefix: {
    type: String,
    required: false,
    default: ''
  },
  suffix: {
    type: String,
    required: false,
    default: ''
  },
  useEasing: {
    type: Boolean,
    required: false,
    default: true
  },
  easingFn: {
    type: Function,
    default(t, b, c, d) {
      return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
    }
  }
})

启动数字动效

const startCount = () => {
  state.localStart = props.start
  state.startTime = null
  state.localDuration = props.duration
  state.paused = false
  state.rAF = requestAnimationFrame(count)
}

核心函数,对数字进行转动

  if (!state.startTime) state.startTime = timestamp
  state.timestamp = timestamp
  const progress = timestamp - state.startTime
  state.remaining = state.localDuration - progress
  // 是否使用速度变化曲线
  if (props.useEasing) {
    if (stopCount.value) {
      state.printVal = state.localStart - props.easingFn(progress, 0, state.localStart - props.end, state.localDuration)
    } else {
      state.printVal = props.easingFn(progress, state.localStart, props.end - state.localStart, state.localDuration)
    }
  } else {
    if (stopCount.value) {
      state.printVal = state.localStart - ((state.localStart - props.end) * (progress / state.localDuration))
    } else {
      state.printVal = state.localStart + (props.end - state.localStart) * (progress / state.localDuration)
    }
  }
  if (stopCount.value) {
    state.printVal = state.printVal < props.end ? props.end : state.printVal
  } else {
    state.printVal = state.printVal > props.end ? props.end : state.printVal
  }

  state.displayValue = formatNumber(state.printVal)
  if (progress < state.localDuration) {
    state.rAF = requestAnimationFrame(count)
  } else {
    emits('callback')
  }
}


// 格式化数据,返回想要展示的数据格式
const formatNumber = (val) => {
  val = val.toFixed(props.default)
  val += ''
  const x = val.split('.')
  let x1 = x[0]
  const x2 = x.length > 1 ? props.decimal + x[1] : ''
  const rgx = /(\d+)(\d{3})/
  if (props.separator && !isNumber(props.separator)) {
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + props.separator + '$2')
    }
  }
  return props.prefix + x1 + x2 + props.suffix
}

取消动效

// 组件销毁时取消动画
onUnmounted(() => {
  cancelAnimationFrame(state.rAF)
})

完整代码

<template>
  {{ state.displayValue }}
</template>

<script setup>  // vue3.2新的语法糖, 编写代码更加简洁高效
import { onMounted, onUnmounted, reactive } from "@vue/runtime-core";
import { watch, computed } from 'vue';
import { requestAnimationFrame, cancelAnimationFrame } from './requestAnimationFrame.js'
// 定义父组件传递的参数
const props = defineProps({
  start: {
    type: Number,
    required: false,
    default: 0
  },
  end: {
    type: Number,
    required: false,
    default: 0
  },
  duration: {
    type: Number,
    required: false,
    default: 5000
  },
  autoPlay: {
    type: Boolean,
    required: false,
    default: true
  },
  decimals: {
    type: Number,
    required: false,
    default: 0,
    validator (value) {
      return value >= 0
    }
  },
  decimal: {
    type: String,
    required: false,
    default: '.'
  },
  separator: {
    type: String,
    required: false,
    default: ','
  },
  prefix: {
    type: String,
    required: false,
    default: ''
  },
  suffix: {
    type: String,
    required: false,
    default: ''
  },
  useEasing: {
    type: Boolean,
    required: false,
    default: true
  },
  easingFn: {
    type: Function,
    default(t, b, c, d) {
      return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
    }
  }
})

const isNumber = (val) => {
  return !isNaN(parseFloat(val))
}

// 格式化数据,返回想要展示的数据格式
const formatNumber = (val) => {
  val = val.toFixed(props.default)
  val += ''
  const x = val.split('.')
  let x1 = x[0]
  const x2 = x.length > 1 ? props.decimal + x[1] : ''
  const rgx = /(\d+)(\d{3})/
  if (props.separator && !isNumber(props.separator)) {
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + props.separator + '$2')
    }
  }
  return props.prefix + x1 + x2 + props.suffix
}

// 相当于vue2中的data中所定义的变量部分
const state = reactive({
  localStart: props.start,
  displayValue: formatNumber(props.start),
  printVal: null,
  paused: false,
  localDuration: props.duration,
  startTime: null,
  timestamp: null,
  remaining: null,
  rAF: null
})

// 定义一个计算属性,当开始数字大于结束数字时返回true
const stopCount = computed(() => {
  return props.start > props.end
})
// 定义父组件的自定义事件,子组件以触发父组件的自定义事件
const emits = defineEmits(['onMountedcallback', 'callback'])

const startCount = () => {
  state.localStart = props.start
  state.startTime = null
  state.localDuration = props.duration
  state.paused = false
  state.rAF = requestAnimationFrame(count)
}

watch(() => props.start, () => {
  if (props.autoPlay) {
    startCount()
  }
})

watch(() => props.end, () => {
  if (props.autoPlay) {
    startCount()
  }
})
// dom挂在完成后执行一些操作
onMounted(() => {
  if (props.autoPlay) {
    startCount()
  }
  emits('onMountedcallback')
})
// 暂停计数
const pause = () => {
  cancelAnimationFrame(state.rAF)
}
// 恢复计数
const resume = () => {
  state.startTime = null
  state.localDuration = +state.remaining
  state.localStart = +state.printVal
  requestAnimationFrame(count)
}

const pauseResume = () => {
  if (state.paused) {
    resume()
    state.paused = false
  } else {
    pause()
    state.paused = true
  }
}

const reset = () => {
  state.startTime = null
  cancelAnimationFrame(state.rAF)
  state.displayValue = formatNumber(props.start)
}

const count = (timestamp) => {
  if (!state.startTime) state.startTime = timestamp
  state.timestamp = timestamp
  const progress = timestamp - state.startTime
  state.remaining = state.localDuration - progress
  // 是否使用速度变化曲线
  if (props.useEasing) {
    if (stopCount.value) {
      state.printVal = state.localStart - props.easingFn(progress, 0, state.localStart - props.end, state.localDuration)
    } else {
      state.printVal = props.easingFn(progress, state.localStart, props.end - state.localStart, state.localDuration)
    }
  } else {
    if (stopCount.value) {
      state.printVal = state.localStart - ((state.localStart - props.end) * (progress / state.localDuration))
    } else {
      state.printVal = state.localStart + (props.end - state.localStart) * (progress / state.localDuration)
    }
  }
  if (stopCount.value) {
    state.printVal = state.printVal < props.end ? props.end : state.printVal
  } else {
    state.printVal = state.printVal > props.end ? props.end : state.printVal
  }

  state.displayValue = formatNumber(state.printVal)
  if (progress < state.localDuration) {
    state.rAF = requestAnimationFrame(count)
  } else {
    emits('callback')
  }
}
// 组件销毁时取消动画
onUnmounted(() => {
  cancelAnimationFrame(state.rAF)
})
</script>

总结

自己封装数字动态效果需要注意各个浏览器直接的差异,手动pollyfill,暴露出去的props参数需要有默认值,数据的格式化可以才有正则表达式的方式,组件的驱动必须是数据变化,根据数据来驱动页面渲染,防止页面出现卡顿,不要强行操作dom,引入的组件可以全局配置,后续组件可以服用,码字不易,请各位看官大佬多多支持,一键三连了~❤️❤️❤️

demo演示

后续的线上demo演示会放在
demo演示
完整代码会放在
个人主页

希望对vue开发者有所帮助~

  1. 个人简介:承吾
  2. 工作年限:5年前端
  3. 地区:上海
  4. 个人宣言:立志出好文,传播我所会的,有好东西就及时与大家共享!
    请添加图片描述
    请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/405006.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

idea如何导入jar包

通过添加Libraries的方式引入&#xff1a; 1、首先在根目录下创建一个 libs 的目录 2、打开 File -> Project Structure 3、单击 Libraries -> "" -> "Java" -> 选择我们导入的项目主目录&#xff0c;点击OK 4、注意&#xff1a;在弹出的方框…

Vite 完整版详解

目录 序论&#xff1a; vite架子分析 1、 打包构建&#xff1a; 2、环境变量 3、模式 4、兼容老浏览器 5、typescript相关 6、基本配置 核心配置全集 推荐两个插件插件Volar 、 Vue 3 Snippets 序论&#xff1a; 开发环境&#xff1a;ESMHMR:来实现模块的热更新;类…

前端项目性能优化方案有哪些

目录 一、 加载优化&#xff08;减少http请求数&#xff09; 二、图片优化 三、使用CDN 四、开启Gzip&#xff08;代码压缩&#xff09; 六、减少不必要的Cookie 七、脚本优化 八、前端代码结构的优化 九、SEO优化 一、 加载优化&#xff08;减少http请求数&#xff09…

vue中axios的二次封装——vue 封装axios详细步骤

一、为什么要封装axios api统一管理&#xff0c;不管接口有多少&#xff0c;所有的接口都可以非常清晰&#xff0c;容易维护。 通常我们的项目会越做越大&#xff0c;页面也会越来越多&#xff0c;如果页面非常的少&#xff0c;直接用axios也没有什么大的影响&#xff0c;那页面…

vue3的setup的使用和原理解析

1.前言 最近在做vue3相关的项目&#xff0c;用到了组合式api&#xff0c;对于vue3的语法的改进也是大为赞赏&#xff0c;用起来十分方便。对于已经熟悉vue2写法的同学也说&#xff0c;上手还是需要一定的学习成本&#xff0c;有可能目前停留在会写会用的阶段&#xff0c;但是s…

Swagger-的使用(详细教程)

文章目录前言一、简介二、基本使用1. 导入相关依赖2. 编写配置文件2.1 配置基本信息2.2 配置接口信息2.3 配置分组信息3. 控制 Swagger 的开启4. 常用注解使用ApiModelApiModelPropertyApiOperationApiParam5. 接口调用三、进阶使用1. 添加请求头四、项目下载前言 作为后端开放…

37.JavaScript对象与JSON格式的转换,JSON.stringify、JSON.parse方法的使用方法和注意事项

文章目录JSON处理JSON.stringifystringify的限制排除和替换映射函数格式化使用的空格数量自定义toJSON方法JSON.parse使用reviver总结JSON处理 JSON&#xff08;JavaScript Object Notation&#xff09;是JavaScript表达值和对象的通用数据格式&#xff0c;其本质就是符合一定…

2023前端面试题及答案整理(JavaScript)

JS类型 string&#xff0c;number&#xff0c;boolean&#xff0c;undefined&#xff0c;null&#xff0c;symbol&#xff08;es6&#xff09;&#xff0c;BigInt&#xff08;es10&#xff09;&#xff0c;object 值类型和引用类型的区别 两种类型的区别是&#xff1a;存储位…

Js各种时间转换问题(YYYY-MM-DD 时间戳 中国标准时间)

1. 类型总结 指定格式 YYYY-MM-DD HH:MM:SS时间戳中国标准时间 Sat Jan 30 2022 08:26:26 GMT0800 (中国标准时间) new Date()获得系统当前时间就会是这种形式 2. 类型之间的转换 时间戳转换为 yyyy-mm-dd或yyyy-MM-dd HH-mm-ss function timestampToTime(timestamp) {var …

【vue】 配置代理

文章目录参考文档跨域问题引入配置代理解决跨域问题&#xff1a;方法一&#xff1a;方法二&#xff1a;使用方法二最终的文件&#xff1a;总结参考文档 尚硅谷视频&#xff1a;https://www.bilibili.com/video/BV1Zy4y1K7SH?p95 axios官网教程&#xff1a;https://axios-htt…

uniapp分包,小程序分包处理,详解(图解),手把手从0开始

一、为什么要分包 因小程序有体积和资源加载限制&#xff0c;优化小程序的下载和启动速度。 二、主包和分包 所谓的主包&#xff0c;即放置默认启动页面/TabBar 页面&#xff0c;以及一些所有分包都需用到公共资源/JS 脚本&#xff1b;而分包则是根据pages.json的配置进行划…

微信小程序详细教程(建议收藏)

一.小程序的开发准备 1. 小程序的安装与创建 第一步 打开小程序官网第二步 找到开发管理&#xff0c;找到开发设置&#xff0c;下面有一个AppID&#xff0c;复制即可&#xff0c;后面开发小程序需要用 新建项目 &#xff0c;需要先下载微信开发工具下载网址&#xff0c;安装完…

九个前端神奇库,让你的前端项目瞬间美化,甲方看了都落泪

九个前端神奇库&#xff0c;让你的前端项目瞬间美化&#xff0c;甲方看了都落泪 九个前端神奇库 文章目录九个前端神奇库&#xff0c;让你的前端项目瞬间美化&#xff0c;甲方看了都落泪1. Lottie-web/Bodymovin2. Parallax.js3. Magic Grid4. webslides5. SVG.js6. rellax7. …

【Vue面试专题】50+道经典Vue面试题详解!

目录前言相关学习资源01-Vue组件之间通信方式有哪些02-v-if和v-for哪个优先级更高&#xff1f;03-能说一说双向绑定使用和原理吗&#xff1f;04-Vue中如何扩展一个组件05-子组件可以直接改变父组件的数据么&#xff0c;说明原因06-Vue要做权限管理该怎么做&#xff1f;控制到按…

hexo主题应用

可以在hexo主题官网自己选择,官网网址:主题,选择哪个全凭自己的喜好。 我选择的一个主题是stun,官网效果图 安装主题stun git clone https://github.com/liuyib/hexo-theme-stun.git themes/stun安装依赖 git clone -b dist https://github.com/liuyib/hexo-theme-stun…

前端常见面试八股文

HTML篇 1、H5新增标签有哪些&#xff1f; 一、语义化标签 header、footer、nav、aside、section、article 语义化的意义&#xff1f; 1、更适合搜索引擎的爬虫爬取有效的信息&#xff0c;利于SEO。 2、对开发团队很友好&#xff0c;增加了标签的可读性&#xff0c;结构更…

VScode 看这一篇就够了

VScode 小白入门教程 VScode 小白入门教程 VScode简介VScode的下载与安装VScode的常用设置 基础设置禁用自动更新自动保存设置Vscode更换主题 VScode的常用快捷键开发人员常用的VScode插件使用VScode开始你的第一行C/C代码 VScode简介 VScode全称是Visual Studio Code&…

一文吃透JavaScript程序控制流与函数

文章目录思维导图&#x1f496;程序控制流⛳️顺序结构⛳️分支结构&#x1f4ab;比较运算符&#x1f4ab;逻辑运算符&#x1f4ab;if语句&#x1f4ab;switch语句⛳️循环结构&#x1f4ab;while语句&#x1f4ab;do...while语句&#x1f4ab;for语句&#x1f4ab;break和cont…

【小程序开发】uniapp引入iconfont图标及使用方式

&#x1f9ca; 前言 本文主要讲述的是在使用uniapp中如何引入iconfont图标&#xff0c;以及两种常用的位置。 位置一&#xff1a;App下原生导航栏的按钮使用字体图标。位置二&#xff1a;页面中的任意位置使用iconfont图标。 &#x1f33a; 正文 第一步&#xff1a;打开iconfo…

HTML爱心网页制作[樱花+爱心]

HTMLCSSJavaScript实现 先点赞后观看,养成好习惯 “不想动手的小伙伴可以直接拿网盘成品” 阿里云盘------提取码: 0d5j 效果图 注:任意浏览器都可以,建议使用谷歌浏览器 代码部分 代码如下仅供参考 可以直接拿去复制粘贴 <!DOCTYPE html> <html><head>…