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


    前言

    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。

    文件目录

    文件目录

    使用示例

    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    入口文件index.js

    
    const UILib = {
      install(Vue) {
        Vue.component('CountTo', CountTo)
      }
    }
    
    export default UILib
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    main.js使用

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

    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)
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    完整代码:

    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 }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    CountTo.vue组件思路

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

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

    需要接受的参数:

    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;
        }
      }
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    启动数字动效

    const startCount = () => {
      state.localStart = props.start
      state.startTime = null
      state.localDuration = props.duration
      state.paused = false
      state.rAF = requestAnimationFrame(count)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

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

      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
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    取消动效

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

    完整代码

    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202

    总结

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

    demo演示

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

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

    1. 个人简介:承吾
    2. 工作年限:5年前端
    3. 地区:上海
    4. 个人宣言:立志出好文,传播我所会的,有好东西就及时与大家共享!
      请添加图片描述
      请添加图片描述
  • 相关阅读:
    2022/08/12、13 day04/05:IDEA中设置Maven、导入与Maven常用设置
    【快速上手系列】使用MD5加密对密码进行加密
    Linux开发工具(5)——git
    React-函数组件的特性与闭包
    Spring MVC中如何对异常进行处理呢?
    哈希表
    worthington酶活性研究丨worthington pH值的影响
    通达信自动交易股票下单程序,外挂软件不可信,实际上券商有现成的接口,个人账户就可以无门槛开启,代码示例
    《Effective Java 中文版》读书笔记
    674. 最长连续递增序列 718. 最长重复子数组 1143.最长公共子序列 1035.不相交的线
  • 原文地址:https://blog.csdn.net/weixin_42974827/article/details/126831847