首页 > 语言 > JavaScript > 正文

基于Vue过渡状态实例讲解

2024-05-06 15:26:46
字体:
来源:转载
供稿:网友

前面的话

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 多边形也可以实现很多难以想象的效果

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选