vue2 手写轮播图组件
时间: 2023-09-27 15:03:56 浏览: 113
好的,下面是一个简单的手写轮播图组件的实现:
```html
<template>
<div class="carousel">
<!-- 可视区域 -->
<div class="viewport">
<div class="slider" :style="{ transform: `translateX(${translateX}px)` }">
<div class="slide" v-for="(item, index) in items" :key="index">
<img :src="item.imgUrl" alt="">
</div>
</div>
</div>
<!-- 控制按钮 -->
<div class="buttons">
<button class="prev" @click="prev"><</button>
<button class="next" @click="next">></button>
</div>
<!-- 指示器 -->
<div class="indicators">
<span class="indicator" v-for="(item, index) in items" :key="index" :class="{ active: index === currentIndex }"
@click="jumpTo(index)"></span>
</div>
</div>
</template>
<script>
export default {
name: 'Carousel',
props: {
items: {
type: Array,
default: () => []
}
},
data() {
return {
currentIndex: 0, // 当前显示的图片索引
translateX: 0 // slider 的 translateX 值
}
},
methods: {
// 切换到上一张图片
prev() {
if (this.currentIndex > 0) {
this.currentIndex--;
this.translateX += this.slideWidth;
} else {
this.currentIndex = this.items.length - 1;
this.translateX = -this.slideWidth * (this.items.length - 1);
}
},
// 切换到下一张图片
next() {
if (this.currentIndex < this.items.length - 1) {
this.currentIndex++;
this.translateX -= this.slideWidth;
} else {
this.currentIndex = 0;
this.translateX = 0;
}
},
// 跳转到指定图片
jumpTo(index) {
this.currentIndex = index;
this.translateX = -this.slideWidth * index;
}
},
computed: {
slideWidth() {
return this.$refs.slider.offsetWidth;
}
}
}
</script>
<style scoped>
.carousel {
position: relative;
width: 100%;
overflow: hidden;
}
.viewport {
position: relative;
overflow: hidden;
}
.slider {
display: flex;
transition: transform 0.3s ease-out;
}
.slide {
flex-shrink: 0;
width: 100%;
text-align: center;
}
.buttons {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 1;
}
.buttons button {
font-size: 2rem;
color: #fff;
background-color: rgba(0, 0, 0, 0.5);
border: none;
outline: none;
cursor: pointer;
padding: 0.5rem;
margin: 0 1rem;
}
.indicators {
position: absolute;
bottom: 1rem;
left: 50%;
transform: translateX(-50%);
z-index: 1;
display: flex;
}
.indicator {
width: 1rem;
height: 1rem;
border-radius: 50%;
background-color: #fff;
margin: 0 0.5rem;
cursor: pointer;
}
.indicator.active {
background-color: #f00;
}
</style>
```
这个组件的主要思路是利用 flex 布局和 translateX 属性实现图片的滑动。其中,控制按钮和指示器使用了绝对定位的方式进行布局。具体实现过程中,我们需要获取 slider 的宽度,以便计算出 translateX 的值。同时,我们还需要在切换到第一张或最后一张图片时,调整 translateX 的值,以实现循环滑动的效果。
阅读全文
相关推荐















