Vue.jsとTween.jsを使用した値の補間
提供:Dev Guides
ウェブサイトでそれらの派手なカウンターのものを見たことがありますか? あなたが知っている、それらの数は時間とともに増加し、その間のすべての小さな数を数えますか? さて、あなたが自分でそれをすることを探しているなら、あなたは正しい場所に来ました。 VueとTween.jsを使用すると、同じ種類のものを数分で実装できます。
基本的なVueプロジェクトがすでに設定されていることを前提としています。 そうでなければ、それはかなり簡単です。
インストール
まず、YarnまたはNPMを使用してtween.jsをインストールしましょう。
# Yarn $ yarn add @tweenjs/tween.js # NPM $ npm install @tweenjs/tween.js
使用法
次に、すべてのアニメーションロジックを保持するクイックラッパーコンポーネントを作成しましょう。 実際にスタイリングする必要はありません。
AnimatedCounter.vue
<template> <span class="tweened-number">{{ tweeningValue }}</span> </template> <script> export default { props: { // The value that we'll be tweening to. value: { type: Number, required: true }, // How long the tween should take. (In milliseconds.) tweenDuration: { type: Number, default: 500 } }, watch: { // Whenever `props.value` changes, update the tween. value(newVal, oldVal) { this.tween(oldVal, newVal) } }, // This holds the temporary state of the tweened value. data() { return { tweeningValue: 0 } }, mounted() { this.tween(0, this.value) }, methods: { // This is our main logic block. It handles tweening from a start value to an end value. tween(start, end) { let frameHandler // Handles updating the tween on each frame. const animate = function (currentTime) { TWEEN.update(currentTime) frameHandler = requestAnimationFrame(animate) } const myTween = new TWEEN.Tween({ tweeningValue: start }) .to({ tweeningValue: end }, this.tweenDuration) // Be careful to not to do too much here! It will slow down the app. .onUpdate(() => { this.tweeningValue = myTween.tweeningValue.toFixed(0) }) .onComplete(() => { // Make sure to clean up after ourselves. cancelAnimationFrame(frameHandler) }) // This actually starts the tween. .start() frameHandler = requestAnimationFrame(animate) } } } </script>
これで、このコンポーネントを次のように使用できます。
ExampleComponent.vue
<template> <div> <p>This number does move-y things. <animated-counter :value="myValue"></animated-counter></p> <p>You can change the tweened number here: <input type="text" v-model="myValue"/></p> <!-- It transitions like magic! Magic with a bunch of code behind it, that is. --> </div> </template> <script> import AnimatedCounter from './AnimatedCounter.vue'; export default { components: { AnimatedCounter }, data() { return { myValue: 100 } } } </script>
これですべてです。 他のいくつかのライブラリを使用すると、文字列、配列、色など、他の値をトゥイーンすることもできます。
詳細については、Tween.jsおよびVue.jsドキュメントを参照してください。