不正确使用Vue过渡?

时间:2018-03-01 08:57:18

标签: javascript vue.js vuejs2 transition

我有一个元素充当图像轮播,每隔3秒换一srcimg

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元素的转换之外,其他所有功能都有效。有关其无效的原因的任何建议吗?

1 个答案:

答案 0 :(得分:1)

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

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

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