【问题标题】:improper use of Vue transition?Vue过渡使用不当?
【发布时间】:2018-03-01 08:57:18
【问题描述】:

我有一个元素充当图像轮播,每 3 秒更换一次imgsrc

JS

data() {

 return {

  carousel: {

    images: [
      "/images/beauty.png",
      "/images/dance.png",
      "/images/funny.png",
      "/images/sweet.png"
    ],
    currentNumber: 0,
    timer: null 
  }   
 } 
}

methods: {
  startRotation: function() {
    this.carousel.timer = setInterval(this.next, 3000);
  },
  next: function() {
    this.carousel.currentNumber += 1
  }
}

标记

<div class="grid__slide">
  <div class="grid__slide-inner" v-for="number in [carousel.currentNumber]">
    <transition
      name="ease-out-transition"
      leave-active-class="fadeOut"
      mode="out-in"
      >
      <img :src="carousel.images[Math.abs(carousel.currentNumber) % carousel.images.length]">
    </transition>
  </div>
</div>

CSS

@keyframes fadeOut {
  from {
    opacity: 1;
  }

  to {
    opacity: 0;
  }
}

.fadeOut {
  -webkit-animation-name: fadeOut;
  animation-name: fadeOut;
    -webkit-animation-duration: 500ms;
    animation-duration: 500ms;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    animation-iteration-count: 1;
    animation-timing-function: cubic-bezier(0.19, 1, 0.22, 1);
}

除了包裹img 元素的过渡之外,一切都起作用。关于为什么它无效的任何建议?

【问题讨论】:

  • 在图片中添加一个:key,这样transition就可以看到元素的变化,而不是它的内容
  • 过渡适用于元素,而不适用于属性更改。您可以使用:key="..." 为图像元素分配一个新键。至少这应该工作:) 编辑:Ferrybig 打败了我!

标签: javascript vue.js vuejs2 transition


【解决方案1】:

正如章节"Transitioning Between Elements" in the documentation about &lt;transition&gt; 中所述,当您尝试在多个相同类型的元素之间进行转换时,您需要添加一个:key 元素。

<img
    :src="carousel.images[Math.abs(carousel.currentNumber) % carousel.images.length]"
    :key="Math.abs(carousel.currentNumber) % carousel.images.length"
>

之所以需要这样做,是因为没有 key 属性,Vue 会尝试优化应用程序的速度,而不是交换图像元素,它只是更改 src 属性以指向您的新图像。

【讨论】:

  • 钥匙,钥匙永远是答案
猜你喜欢
  • 1970-01-01
  • 2017-04-29
  • 2021-08-02
  • 1970-01-01
  • 2020-11-03
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
相关资源
最近更新 更多