效果图
<template>
<div>
<div class="swiper">
<ul ref="swiper" class="swipero">
<li v-for="(item, index) in items" :key="index">
<div v-text="item.name"></div>
</li>
</ul>
</div>
<div @click="preNext()">下一页</div>
<div @click="preLast()">上一页</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: "1" },
{ id: 1, name: "2" },
{ id: 1, name: "3" },
],
timer: null,
active: 0,
flag: true,
};
},
mounted() {
this.init();
},
methods: {
// 初始化克隆一个元素,用来解决视觉差的效果(瞬移)
init() {
let swiper = this.$refs.swiper;
let first = swiper.firstElementChild.cloneNode(true);
swiper.appendChild(first);
},
//下一页
next() {
let swiper = this.$refs.swiper;
// 判断是否是最后一个
// debugger;
if (this.$refs.swiper.children.length - 2 <= this.active) {
// debugger
setTimeout(() => {
let swiper = this.$refs.swiper;
this.active = 0;
swiper.style.transition = "none";
swiper.style.left = -200 * this.active + "px";
}, 500);
}
this.active++;
swiper.style.transition = "all .5s";
swiper.style.left = -200 * this.active + "px";
},
// 上一页
pre() {
let swiper = this.$refs.swiper;
// 判断是否是第一个,线瞬间移动到最后,然后再实现动画效果
if (this.active == 0) {
let len = this.$refs.swiper.children.length;
this.active = len - 1;
// debugger
swiper.style.transition = "none";
swiper.style.left = -200 * this.active + "px";
setTimeout(() => {
this.active = len - 2;
swiper.style.transition = "all .5s";
swiper.style.left = -200 * this.active + "px";
}, 300);
} else {
this.active--;
swiper.style.transition = "all .5s";
swiper.style.left = -200 * this.active + "px";
// this.swiper();
}
},
// 节流
throttle(callback,speed=3000) {
let self = this;
if (self.flag) {
clearTimeout(this.timer);
self.timer = setTimeout(() => {
callback();
self.flag = true;
}, speed);
}
this.flag = false;
},
// 下一页(节流)
preNext() {
this.throttle(this.next,1000);
},
// 上一页(节流)
preLast() {
this.throttle(this.pre,1000);
},
// 自动轮播
swiper() {
let self = this;
setInterval(() => {
self.pre();
}, 3000);
},
},
};
</script>
<style lang="less" scoped>
.swiper {
width: 200px;
height: 200px;
overflow: hidden;
position: relative;
ul {
position: absolute;
bottom: 0;
left: 0;
width: 100vw;
white-space: nowrap;
li {
width: 200px;
height: 200px;
display: inline-block;
vertical-align: bottom;
position: relative;
// margin-right: 20px;
transition: all 0.5s;
> div {
width: 100%;
height: 100%;
}
&:nth-child(1) {
background-color: aquamarine;
}
&:nth-child(2) {
background-color: rgb(255, 204, 127);
}
&:nth-child(3) {
background-color: rgb(255, 127, 144);
}
&:nth-child(4) {
background-color: rgb(127, 255, 223);
}
}
.active {
width: 400px;
height: 400px;
}
}
}
</style>