一、介绍和不足
本篇文章用于记录无缝轮播图的相关代码以及开发过程中的问题和不足。在进行无缝轮播图的开发过程中,我遇到了些问题: 1、在进行无缝切换时,需要等待浏览器进行渲染,但vue3与原生js有所不同,在原生js可以通过获取元素的宽/高,强行等待浏览器渲染后再执行下一步操作,但vue3无法进行此操作。(不知道是不是我写法的问题,也考虑过使用nextTick进行等待,但还是无法实现,无奈只好使用setTimeout强行进行等待)
二、代码展示
只实现了左右切换的无缝效果图片要自己导入,简易版代码如下:
<template>
<div class="container">
<button class="left" @click="prev()"><</button>
<img
:src="item"
alt=""
v-for="item in imgs"
:key="item"
:style="ulWidth"
:class="{ tran: noLast }"
/>
<button class="right" @click="next()">></button>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from "vue";
const imgs = [];
const imgsLength = imgs.length;
imgs.push(imgs[0]);
imgs.unshift(imgs[imgsLength - 1]);
const bar = ref({
transform: "translateX(0)",
});
const noLast = ref(true);
const curIndex = ref(1);
function prev() {
curIndex.value--;
if (curIndex.value == 0) {
setTimeout(() => {
noLast.value = false;
curIndex.value = imgsLength;
}, 500); //定时器的时间等于过渡时间
}
noLast.value = true;
}
function next() {
curIndex.value++;
if (curIndex.value == imgs.length - 1) {
setTimeout(() => {
noLast.value = false;
curIndex.value = 1;
}, 500);
}
noLast.value = true;
}
const ulWidth = computed(() => {
bar.value = {
transform: "translateX(-" + curIndex.value * 100 + "%)",
};
return bar.value;
});
</script>
<style scoped lang="scss">
.container {
margin: 0 auto;
width: 600px;
height: 400px;
background-color: antiquewhite;
display: flex;
overflow: hidden;
flex-wrap: nowrap;
position: relative;
.tran {
transition: all 0.5s;
}
img {
width: 800px;
height: 400px;
object-fit: fill;
}
button {
position: absolute;
top: 50%;
z-index: 999;
}
.left {
left: 10px;
}
.right {
right: 10px;
}
}
</style>