vue數字金額動態(tài)變化功能實現方法詳解
1 前言
在某些場景中,要求我們能夠動態(tài)與用戶進行交互,如頁面加載一個數字的時候,動態(tài)改變一個固定地數字,然后將數字展現在頁面上,如當前的積分或者余額等;以達到提高與用戶交互體驗的效果。下面我們就在vue中使用兩種方法來實現數字動態(tài)滾動效果。
2 數字動態(tài)滾動
2.1 計時器實現
先上效果:

以上效果是點擊按鈕加載金額,實際情況是頁面加載的時候就需要。這個時候我們需要在頁面加載的時候執(zhí)行用該方法。以上實例用到的代碼如下:
代碼:
<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: "動態(tài)變化金額",
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>除了這個效果以外,我們可以通過調節(jié)計時器的間隔時間來控制金額變化的速度;通過調節(jié)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: "動態(tài)變化金額",
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;
// 動畫繼續(xù)
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()是執(zhí)行動畫幀的關鍵方法,對應window.cancelAnimationFrame()是停止動畫幀的方法。其中動畫幀的價格時間一把為16ms,同上,通過調節(jié)framenum參數來控制一共播放多少幀,來達到我們想要的效果。
3 總結
本次用兩種方法實現金額數字等動態(tài)變化,偏向應用領域,若想了解即使器和動畫幀的更深層次原理,請一部專業(yè)網站或者動手艙室一下。
到此這篇關于vue數字金額動態(tài)變化功能實現方法詳解的文章就介紹到這了,更多相關vue數字動態(tài)變化內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue+elementUI實現右擊指定表格列的單元格顯示選擇框功能
這篇文章主要介紹了vue+elementUI實現右擊指定表格列的單元格顯示選擇框功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-03-03

