用vue2写一个轮播图
时间: 2024-03-13 16:35:28 浏览: 60
好的,以下是一个简单的Vue2轮播图实现:
1. 首先在HTML中创建一个轮播图容器,包含图片和导航按钮:
```
<template>
<div class="slider">
<div class="slider-container">
<img v-for="(image, index) in images" :key="index" :src="image.src" :class="{ active: index === activeIndex }">
</div>
<div class="slider-navigation">
<button v-for="(image, index) in images" :key="index" @click="setActiveIndex(index)" :class="{ active: index === activeIndex }"></button>
</div>
</div>
</template>
```
2. 在Vue的data中定义轮播图所需的数据和方法:
```
<script>
export default {
data() {
return {
activeIndex: 0, // 当前显示的图片索引
images: [ // 图片列表
{
src: 'https://picsum.photos/800/400?random=1'
},
{
src: 'https://picsum.photos/800/400?random=2'
},
{
src: 'https://picsum.photos/800/400?random=3'
},
{
src: 'https://picsum.photos/800/400?random=4'
}
]
}
},
methods: {
setActiveIndex(index) { // 设置当前显示的图片索引
this.activeIndex = index
},
next() { // 切换至下一张图片
this.activeIndex++
if (this.activeIndex >= this.images.length) {
this.activeIndex = 0
}
},
prev() { // 切换至上一张图片
this.activeIndex--
if (this.activeIndex < 0) {
this.activeIndex = this.images.length - 1
}
}
},
mounted() { // 自动轮播
setInterval(() => {
this.next()
}, 3000)
}
}
</script>
```
3. 在CSS中定义轮播图样式:
```
<style>
.slider {
position: relative;
overflow: hidden;
}
.slider-container {
display: flex;
transition: transform 0.5s ease;
}
.slider-container img {
width: 100%;
height: auto;
object-fit: cover;
}
.slider-navigation {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.slider-navigation button {
width: 16px;
height: 16px;
border-radius: 50%;
border: none;
margin: 0 10px;
background-color: #ccc;
cursor: pointer;
transition: background-color 0.2s ease;
}
.slider-navigation button.active {
background-color: #333;
}
</style>
```
这样就完成了一个简单的Vue2轮播图实现。
阅读全文