休假过渡期间未应用计算样式

时间:2019-03-14 23:20:42

标签: vue.js

当元素具有计算样式时,如果该元素正在进行离开过渡,则不会应用样式更改:

new Vue({
  el: "#app",
  data: {
    selected: 1,
    items: [{
        color: 'red'
      },
      {
        color: 'blue'
      },
      {
        color: 'green'
      },
    ],
    tweened: {
      height: 50,
    },
  },
  computed: {
    divStyles() {
      return {
        height: this.tweened.height + 'px',
        background: this.displayed.color,
        'margin-left': this.selected * 100 + 'px',
        width: '100px',
      }
    },
    displayed() {
      return this.items[this.selected - 1]
    }
  },
  watch: {
    selected(newVal) {
      function animate() {
        if (TWEEN.update()) {
          requestAnimationFrame(animate)
        }
      }

      new TWEEN.Tween(this.tweened)
        .to({
          height: newVal * 50
        }, 2000)
        .easing(TWEEN.Easing.Quadratic.InOut)
        .start()

      animate()
    }
  },
  methods: {
    toggle: function(todo) {
      todo.done = !todo.done
    }
  }
})
.colored-div {
  opacity: 1;
  position: absolute;
}

.switcher-leave-to,
.switcher-enter {
  opacity: 0;
}

.switcher-enter-to,
.switcher-leave {
  opacity: 1;
}

.switcher-leave-active,
.switcher-enter-active {
  transition: opacity 5s linear;
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/16.3.5/Tween.min.js"></script>

<div id="app">
  <button @click="selected--" :disabled="selected <= 1">
      Previous
    </button>
  <button @click="selected++" :disabled="selected >= 3">
      Next
    </button>
  <span>Selected: {{selected}}</span>
  <transition name="switcher">
    <div v-for="(item, index) in items" v-if="index + 1 === selected" :key="index" :style="divStyles" class="colored-div" />
  </transition>
</div>

https://jsfiddle.net/64syzru5/12/

我希望剩余元素随着其逐渐消失而继续调整大小,但事实并非如此。在leave-active过渡期间,如何将计算的样式应用于剩余元素?

1 个答案:

答案 0 :(得分:0)

由于您使用CSS进行过渡,因此Javascript不会在每个中间步骤执行。这对性能而言是件好事,但这意味着不会重新计算所计算的属性。尽我所能说,不过,您只是尝试设置高度的动画。在纯CSS中很容易做到这一点。使用内联钩子通过内联样式或CSS变量将其设置为初始值,然后在后联钩中删除该属性。

更重要的是,看起来您的应用程序可能更适合于过渡组,而不是简单的过渡。