vue2封装Carousel 组件
时间: 2023-11-04 16:54:24 浏览: 110
VUE 3D轮播图封装实现方法
以下是一个简单的 Vue2 封装 Carousel 组件的示例:
```html
<template>
<div class="carousel">
<div class="slides">
<div class="slide" v-for="(item, index) in items" :key="index">
<img :src="item.imgUrl" alt="">
<h3>{{ item.title }}</h3>
<p>{{ item.description }}</p>
</div>
</div>
<div class="indicators">
<span v-for="(item, index) in items" :key="index" :class="{ active: index === currentIndex }" @click="goTo(index)">{{ index + 1 }}</span>
</div>
<button class="prev" @click="prev"><</button>
<button class="next" @click="next">></button>
</div>
</template>
<script>
export default {
name: 'Carousel',
props: {
items: {
type: Array,
required: true
}
},
data() {
return {
currentIndex: 0
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length
},
goTo(index) {
this.currentIndex = index
}
}
}
</script>
<style>
.carousel {
position: relative;
overflow: hidden;
width: 100%;
height: 400px;
}
.slides {
display: flex;
transition: transform 0.3s ease-in-out;
transform: translateX(-{{ currentIndex }}00%);
}
.slide {
flex-shrink: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.slide img {
max-width: 100%;
max-height: 100%;
}
.indicators {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.indicators span {
width: 10px;
height: 10px;
margin-right: 10px;
border-radius: 50%;
cursor: pointer;
background-color: #ddd;
}
.indicators span.active {
background-color: #000;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
border: none;
background-color: transparent;
font-size: 30px;
color: #fff;
cursor: pointer;
}
.prev {
left: 20px;
}
.next {
right: 20px;
}
</style>
```
使用示例:
```html
<template>
<Carousel :items="items" />
</template>
<script>
import Carousel from './Carousel.vue'
export default {
components: {
Carousel
},
data() {
return {
items: [
{
imgUrl: 'https://picsum.photos/id/1/800/400',
title: 'Slide 1',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
},
{
imgUrl: 'https://picsum.photos/id/2/800/400',
title: 'Slide 2',
description: 'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
},
{
imgUrl: 'https://picsum.photos/id/3/800/400',
title: 'Slide 3',
description: 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
}
]
}
}
}
</script>
```
上面的示例只是一个简单的实现,你可以根据自己的需要进行扩展和优化。
阅读全文