vue利用transition过渡动画实现轮播图

<template>
  <div id="app">
    <ul>
      <li v-for="(item, index) in slideData" :key="index">
        <transition>
          <img :src="item.img" v-if="index === currentIndex" />
        </transition>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      slideData: [
        {
          id: 1,
          img: 'https://img.alicdn.com/imgextra/i2/6000000001117/O1CN01Mn6ES81K7d5SAd6hU_!!6000000001117-0-octopus.jpg'
        },
        {
          id: 2,
          img: 'https://aecpm.alicdn.com/simba/img/TB1XotJXQfb_uJkSnhJSuvdDVXa.jpg'
        },
        {
          id: 3,
          img: 'https://aecpm.alicdn.com/simba/img/TB1JNHwKFXXXXafXVXXSutbFXXX.jpg'
        }
      ],
      currentIndex: 0
    }
  },
  created() {
    this.autoPlay()
  },
  methods: {
    // 自动轮播,每隔 1 秒轮播一次
    autoPlay() {
      setInterval(() => {
        this._setIndex()
      }, 1000)
    },
    // 设置当前索引
    _setIndex() {
      this.currentIndex++
      if (this.currentIndex === this.slideData.length) this.currentIndex = 0
    }
  }
}
</script>
<style lang="less" scoped>
#app {
  > ul {
    position: relative;
    width: 500px;
    height: 284px;
    overflow: hidden;
    img {
      position: absolute;
      top: 0;
      left: 0;
    }
    .v-enter-active,
    .v-leave-active {
      transition: transform 0.5s;
    }
    .v-enter {
      transform: translateX(100%);
    }
    .v-enter-to {
      transform: translateX(0);
    }
    .v-leave {
      transform: translateX(0);
    }
    .v-leave-to {
      transform: translateX(-100%);
    }
  }
}
</style>

 

上一篇:JavaScript手写系列——手写reduce取代map


下一篇:凸起按钮的配置