自由屋推书网—热门的小说推荐平台!

你的位置: 首页 > 网页制作

vue数字金额动态变化功能实现方法详解

2022-09-15 09:40:50

这篇文章主要介绍了vue实现数字金额动态变化效果,数字动态变化是我们在前端开发中经常需要做的效果,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧!

1 前言

在某些场景中,要求我们能够动态与用户进行交互,如页面加载一个数字的时候,动态改变一个固定地数字,然后将数字展现在页面上,如当前的积分或者余额等;以达到提高与用户交互体验的效果。下面我们就在vue中使用两种方法来实现数字动态滚动效果。

2 数字动态滚动

2.1 计时器实现

先上效果:

  以上效果是点击按钮加载金额,实际情况是页面加载的时候就需要。这个时候我们需要在页面加载的时候执行用该方法。以上实例用到的代码如下:

代码:

<template>
  <div>
<title-bar :title="title" @goBack="goback"></title-bar>
 <div class="amount-box">
  <label>您的余额为:</label>
  <label>{{ amountFormatPage }}</label>
</div>
<t-button @clickhandle="changeAmount" name="计时器"></t-button>
  </div>
</template>
<script>
import TitleBar from "@/components/TitleBar";
import tButton from "@/components/TButton";
import { amountFormat } from "@/util/utils";
export default {
  components: {
TitleBar,
tButton
  },
  data() {
return {
  res: false, //
  title: "动态变化金额",
  amount: 0, //初始amout
  amoutFrame: 0,
  amountShow: 0
};
  },
  computed: {
// 计算属性格式化页面金额
amountFormatPage() {
  return amountFormat(this.amount);
}
  },
  methods: {
changeAmount() {
  const total = 16000; //设置初始总金额
  const _this = this;
  let i = 0;
  //变化15次,每次间隔30毫秒
  const amoutInterval = setInterval(() => {
if (i < 15) {
  i++;
  _this.amount = (total * i) / 15;
} else {
  clearInterval(amoutInterval);
}
  }, 30);
},
goback() {
  //
}
  }
};
</script>
<style lang="scss" scoped>
.amount-box {
  label {
display: box;
  }
}
</style>

除了这个效果以外,我们可以通过调节计时器的间隔时间来控制金额变化的速度;通过调节i的大小来控制变化的次数。主要是控制这两个参数来达到我们想要的效果。

2.2 动画帧实现

实现效果如下:

vue代码如下:

<template>
  <div>
<title-bar :title="title" @goBack="goback"></title-bar>
<div>
  <label>您的余额为:</label>
  <label>{{ amountShow }}</label>
</div>
<t-button @clickhandle="changeAmountFrame" name="动画帧"></t-button>
  </div>
</template>
<script>
import TitleBar from "@/components/TitleBar";
import tButton from "@/components/TButton";
import { amountFormat } from "@/util/utils";
export default {
  components: {
TitleBar,
tButton
  },
  data() {
return {
  res: false, //
  title: "动态变化金额",
  amount: 0, //初始amout
  amoutFrame: 0,
  amountShow: 0
};
  },
  methods: {
changeAmountFrame() {
  const total = 26666;
  const frameNum = 60;
  const _this = this;
  let animation = window.requestAnimationFrame(function f() {
if (_this.amoutFrame < total) {
  _this.amoutFrame = _this.amoutFrame + total / frameNum;
  // 动画继续
  animation = window.requestAnimationFrame(f);
} else {
  _this.amoutFrame = total;
  // 动画停止
  window.cancelAnimationFrame(f);
}
_this.amountShow = amountFormat(_this.amoutFrame);
  });
},
goback() {
  //
}
  }
};
</script>
<style lang="scss" scoped>
.amount-box {
  label {
display: box;
  }
}
</style>

window.requestAnimationFrame()是执行动画帧的关键方法,对应window.cancelAnimationFrame()是停止动画帧的方法。其中动画帧的价格时间一把为16ms,同上,通过调节framenum参数来控制一共播放多少帧,来达到我们想要的效果。

3 总结

本次用两种方法实现金额数字等动态变化,偏向应用领域,若想了解即使器和动画帧的更深层次原理,请一部专业网站或者动手舱室一下。

Vue

编辑推荐

热门小说