给我一个轮播图代码vue
时间: 2024-04-16 09:07:57 浏览: 116
以下是一个简单的Vue轮播图代码示例:
```html
<template>
<div class="carousel">
<div class="slide" v-for="(image, index) in images" :key="index" v-show="index === currentSlide">
<img :src="image" alt="Slide">
</div>
<div class="controls">
<button @click="previousSlide">Previous</button>
<button @click="nextSlide">Next</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentSlide: 0,
images: [
"https://via.placeholder.com/800x300?text=Slide+1",
"https://via.placeholder.com/800x300?text=Slide+2",
"https://via.placeholder.com/800x300?text=Slide+3"
]
};
},
methods: {
nextSlide() {
this.currentSlide = (this.currentSlide + 1) % this.images.length;
},
previousSlide() {
this.currentSlide =
(this.currentSlide - 1 + this.images.length) % this.images.length;
}
}
};
</script>
<style>
.carousel {
position: relative;
width: 800px;
height: 300px;
overflow: hidden;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.slide img {
max-width: 100%;
max-height: 100%;
}
.controls {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
justify-content: center;
align-items: center;
}
.controls button {
margin: 0 10px;
padding: 10px;
border: none;
background-color: #ccc;
cursor: pointer;
}
</style>
```
以上代码实现了一个基本的轮播图,图片数组存储了三张图片的链接,使用了Vue的`v-for`指令渲染出每一张图片的`<img>`标签,使用了`v-show`指令根据当前的`currentSlide`变量来决定哪一张图片显示。两个按钮用于切换上一张和下一张图片,点击按钮时更新`currentSlide`变量即可。最后,通过CSS实现了轮播图容器和图片的样式,以及按钮的样式。
阅读全文