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

源码如下:

<template>
	<div class="swiper-container">
		<div class="swiper-wrapper" :style="{flexDirection:`${vertical?'column':'row'}`}">
			<!-- translateY 竖向移动轮播 -->
			<!-- translateX 横向移动轮播 -->
			<!-- vertical -->
			<div class="swiper-slide"
				:style="[{transform:`${animate?vertical?'translateY(-100%)':'translateX(-100%)':'none'}`},{transition: `${animate?'all 1.5s':'none'}`}]"
				v-for="(item,index) in list" :key="index">
				{{item}}
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		props: {
			duration: { //滚动时长
				type: Number,
				default: 4000,
			},
			vertical: { //是否纵向
				type: Boolean,
				default: false,
			}
		},
		data() {
			return {
				list: [1, 2, 3, 4, 5, 6, 7, 8, 9],
				timer: null,
				animate: false,
			}
		},
		computed: {
			time() {

			}
		},
		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 lang="scss">
	.swiper-container {
		width: 100%;
		height: 200px;
		overflow: hidden;
	}

	.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>

Logo

前往低代码交流专区

更多推荐