本篇内容主要讲解“Vue金融数字格式化并保留小数的数字滚动效果怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue金融数字格式化并保留小数的数字滚动效果怎么实现”吧!
Vue金融数字格式化(并保留小数) 数字滚动
提示
我选用的是Vue 过滤器使用,个人觉得比较方便,不过过滤器不支持Vue3,你可以封装成方法嘛都行,下面我以过滤器的形式展示出来
  filters: {
    // 截取字符串
    subStringText(value, index) {
      const str = String(value);
      if (!value) return 0;
      return str.length > index ? str.substring(0, index) + '...' : str;
    },
   // 格式化数字
    formatNumber(num,decimals) {
      num = num.toFixed(decimals);
      num += '';
      const x = num.split('.');
      let x1 = x[0];
      const x2 = x.length > 1 ? '.' + x[1] : '';
      const rgx = /(d+)(d{3})/;
      if (',' && isNaN(parseFloat(','))) {
        while (rgx.test(x1)) {
          x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
      }
      return  x1 + x2;
    },
  },使用:
有个插件 -- 可以轻松实现数字滚动并且数字格式化,推荐vue-count-to ,非常友好,补充:vue做数字滚动效果
vue实现数字滚动效果
近期在做项目的时候,产品要求实现数字滚动效果如下:
用jquery实现
html: <div class="develop"> <!--滚动的数字--> <p><span class="shuzi">3000000</span></p> <p><span class="shuzi">60000</span></p> </div>
js:
$(".navigation_right li").click(function () {
    $(this).siblings('li').removeClass("yanse");
  });
  let arr = $(".develop>p>.shuzi");
  arr.each(function(e, a){
    let num = $(a).text()
    let i = 0;
    let count = parseInt(num /500);
    let timer = setInterval(function(){
      $(a).text(i)
      i += count;
      if (i > num)
        window.clearInterval(timer)
    }, 5)
  })这样做有一个问题,只能和500取余且为整数,而且滚动的时间也没发控制,显然是不满足我们的业务场景的。
用vue-countTo实现
vue-countTo是一个无依赖,轻量级的vue组件,可以自行覆盖easingFn。
安装使用
npm install vue-count-to
例子
<template>
  <countTo :startVal='startVal' :endVal='endVal' :duration='3000'></countTo>
</template>
<script>
//直接引入组件'vue-count-to'
  import countTo from 'vue-count-to';
  export default {
  //注册组件
    components: { countTo },
    data () {
      return {
      //数字开始
        startVal: 0,
       //数字结束
        endVal: 50000
      }
    }
  }
</script>其中:startVal为开始数字,startVal为结束数字,duration为滚动时长, decimal:保留小数点后几位
| Property | Description | type | default | 
|---|---|---|---|
| startVal | 开始值 | Number | 0 | 
| endVal | 结束值 | Number | 2017 | 
| duration | 持续时间,以毫秒为单位 | Number | 3000 | 
| autoplay | 自动播放 | Boolean | true | 
| decimals | 要显示的小数位数 | Number | 0 | 
| decimal | 十进制分割 | String | . | 
| separator | 分隔符 | String | , | 
| prefix | 前缀 | String | '' | 
| suffix | 后缀 | String | '' | 
| useEasing | 使用缓和功能 | Boolean | true | 
| easingFn | 缓和回调 | Function | — | 
** 注意:当autoplay:true时,它将在startVal或endVal更改时自动启动**
| Function Name | Description | 
|---|---|
| mountedCallback | 挂载以后返回回调 | 
| start | 开始计数 | 
| pause | 暂停计数 | 
| reset | 重置countTo |