不正确使用Vue过渡?

问题描述 投票:1回答:1

我有一个元素充当图像轮播通过每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元素的过渡之外,一切都起作用。有什么建议,为什么它无效?

javascript vue.js vuejs2 transition
1个回答
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属性更改为指向新图像。

© www.soinside.com 2019 - 2024. All rights reserved.