vue实现横向或竖向滑动轮播

利用数组push()和shift()方法,每次滑动一个item项,将滑动过去的item项移除掉并添加到数组的最后,实现无缝循环滑动.

 

源码如下:

<template>
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <!--transform: translate(-100%); translateY 竖向移动轮播 -->
      <div
        class="swiper-slide"
        :style="{transform:`${animate?'translate(-100%)':'none'}`,transition: `${animate?'all '+(duration/2000)+'s':'none'}`}"
        v-for="(item,index) in list"
        :key="index">
        {{item}}
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        list: [1, 2, 3, 4, 5, 6, 7, 8, 9],
        timer: null,
        animate: false,
        duration: 3000,
      }
    },
    created() {
      this.timer = setInterval(this.scroll, this.duration);
    },
    methods: {
      scroll() {
        this.animate = true;    // 因为在消息向上滚动的时候需要添加css3过渡动画,所以这里需要设置true
        setTimeout(() => {
          this.list.push(this.list.shift());  //删除数组的第一个元素并添加到数组的最后一项
          this.animate = false;  //滑动完成后取消过渡动画,实现无缝滚动
        }, this.duration / 2);//滑动item项必须要在每次轮播开始前,所以时间必须比duration短
      },
    }
  }
</script>

<style scoped>
  .swiper-container {
    width: 100%;
    height: 200px;
  }

  .swiper-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
  }

  .swiper-slide {
    width: 300px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid;
  }
</style>

 


版权声明:本文为XinYe666666原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。