vue.js实现轮播图
时间: 2023-09-23 13:03:26 浏览: 168
Vue.js可以通过使用第三方插件或者自己编写组件来实现轮播图。以下是一个常用的方式:
1. 使用vue-awesome-swiper插件
vue-awesome-swiper是一个基于Swiper的轮播图插件,可以快速实现轮播图功能。
安装:
```
npm install vue-awesome-swiper --save
```
使用:
```html
<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="item in list" :key="item.id">
<img :src="item.imgUrl" alt="">
</div>
</div>
<div class="swiper-pagination"></div>
</div>
</template>
<script>
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
export default {
components: {
swiper,
swiperSlide
},
data() {
return {
list: [
{
id: 1,
imgUrl: 'http://xxx/1.jpg'
},
{
id: 2,
imgUrl: 'http://xxx/2.jpg'
},
{
id: 3,
imgUrl: 'http://xxx/3.jpg'
}
],
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
loop: true
}
}
},
mounted() {
console.log('mounted')
}
}
</script>
```
2. 自己编写组件
如果需要自定义轮播图的样式和交互,可以自己编写组件实现。
```html
<template>
<div class="carousel">
<div class="carousel-item" v-for="(item, index) in list" :key="index">
<img :src="item.imgUrl" alt="">
</div>
<div class="carousel-nav">
<span class="carousel-nav-item"
v-for="(item, index) in list"
:key="index"
:class="{active: currentIndex === index}"
@click="handleClick(index)">
</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{
id: 1,
imgUrl: 'http://xxx/1.jpg'
},
{
id: 2,
imgUrl: 'http://xxx/2.jpg'
},
{
id: 3,
imgUrl: 'http://xxx/3.jpg'
}
],
currentIndex: 0
}
},
mounted() {
this.autoPlay()
},
methods: {
autoPlay() {
setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.list.length
}, 2000)
},
handleClick(index) {
this.currentIndex = index
}
}
}
</script>
<style scoped>
.carousel {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.carousel-item {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.3s;
}
.carousel-item.active {
opacity: 1;
}
.carousel-nav {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.carousel-nav-item {
width: 10px;
height: 10px;
margin-right: 10px;
border-radius: 50%;
background-color: #fff;
cursor: pointer;
}
.carousel-nav-item.active {
background-color: #f00;
}
</style>
```
阅读全文