經(jīng)常遇到這樣的效果,數(shù)字的變化,比如從 0 到 500 這樣的滔驾。
直接變當(dāng)然是可以的,但是加一些緩動(dòng)效果用戶體驗(yàn)會(huì)更好俄讹。
假設(shè)你在一個(gè)vue的項(xiàng)目中
安裝依賴:
npm install --save @tweenjs/tween.js
或者直接使用cdn:
<script src="https://cdn.bootcss.com/tween.js/r14/Tween.min.js"></script>
簡(jiǎn)單效果圖:
image.png
代碼如下:
html:
<div id="app">
<button @click="change">start</button>
<button @click="reset">reset</button>
<div>init-num: {{num}}</div>
<div>tween-num: {{numTween}}</div>
</div>
css:
body {
display: flex;
height: 100vh;
}
#app {
margin: auto;
width: 300px;
}
js:
import TWEEN from '@tweenjs/tween.js'
new Vue({
el: '#app',
data () {
return {
num: 0,
numTween: 0
}
},
watch: {
num (newValue, oldValue) {
new TWEEN.Tween({
number: oldValue
})
.to({
number: newValue
}, 5000)
.onUpdate(tween => {
this.numTween = tween.number.toFixed(0)
})
.start()
function animate() {
if (TWEEN.update()) {
requestAnimationFrame(animate);
}
}
animate()
}
},
methods: {
change () {
this.num = 500
},
reset () {
this.num = 0
}
}
})
具體做法:
結(jié)合了 vue 的 watch 和 tween.js 的功能 輕松實(shí)現(xiàn)了數(shù)字的緩動(dòng)
具體demo vue number tween by 潘家大少爺 (@jackpan) on CodePen.