前面的話
Vue 的過渡系統提供了非常多簡單的方法設置進入、離開和列表的動效。那么對于數據元素本身的動效呢?包括數字和運算、顏色的顯示、SVG 節點的位置、元素的大小和其他的屬性等。所有的原始數字都被事先存儲起來,可以直接轉換到數字。做到這一步,我們就可以結合 Vue 的響應式和組件系統,使用第三方庫來實現切換元素的過渡狀態
狀態動畫
通過watcher,能監聽到任何數值屬性的數值更新
<div id="animated-number-demo"> <input v-model.number="number" type="number" step="20"> <p>{{ animatedNumber }}</p></div><script src="Tween.js"></script><script src="vue.js"></script> <script>new Vue({ el: '#animated-number-demo', data: { number: 0, animatedNumber: 0 }, watch: { number: function(newValue, oldValue) { var vm = this; function animate () { if (TWEEN.update()) { requestAnimationFrame(animate) } } new TWEEN.Tween({ tweeningNumber: oldValue }) .easing(TWEEN.Easing.Quadratic.Out) .to({ tweeningNumber: newValue }, 500) .onUpdate(function () { vm.animatedNumber = this.tweeningNumber.toFixed(0) }) .start(); animate() } }}) </script>當把數值更新時,就會觸發動畫。這個是一個不錯的演示,但是對于不能直接像數字一樣存儲的值,比如 CSS 中的 color 的值,通過下面的例子來通過 Color.js 實現一個例子:
<div id="example"> <input v-model="colorQuery" @keyup.enter="updateColor" placeholder="Enter a color"> <button @click="updateColor">Update</button> <p>Preview:</p> <span :style="{ backgroundColor: tweenedCSSColor }" style="display: inline-block;width: 50px;height: 50px;"></span> <p>{{ tweenedCSSColor }}</p></div><script src="Tween.js"></script><script src="vue.js"></script> <script src="color.js"></script><script>var Color = net.brehaut.Colornew Vue({ el: '#example', data: { colorQuery: '', color: { red: 0, green: 0, blue: 0, alpha: 1 }, tweenedColor: {} }, created: function () { this.tweenedColor = Object.assign({}, this.color) }, watch: { color: function () { function animate () { if (TWEEN.update()) { requestAnimationFrame(animate) } } new TWEEN.Tween(this.tweenedColor) .to(this.color, 750) .start() animate() } }, computed: { tweenedCSSColor: function () { return new Color({ red: this.tweenedColor.red, green: this.tweenedColor.green, blue: this.tweenedColor.blue, alpha: this.tweenedColor.alpha }).toCSS() } }, methods: { updateColor: function () { this.color = new Color(this.colorQuery).toRGB() this.colorQuery = '' } }})</script>動態狀態轉換
就像 Vue 的過渡組件一樣,數據背后狀態轉換會實時更新,這對于原型設計十分有用。當修改一些變量,即使是一個簡單的 SVG 多邊形也可以實現很多難以想象的效果
新聞熱點
疑難解答
圖片精選