vue2中使用swiper轮播图
时间: 2023-11-26 20:03:40 浏览: 66
Vue封装Swiper实现图片轮播效果
1.首先安装swiper
```
npm install swiper --save
```
2.在需要使用轮播图的组件中导入swiper
```
import Swiper from 'swiper'
import 'swiper/dist/css/swiper.css'
```
3.在组件的mounted生命周期中初始化swiper
```
mounted() {
new Swiper('.swiper-container', {
// 轮播图配置项
})
}
```
4.在模板中添加轮播图结构
```
<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
<img src="图片地址" alt="">
</div>
<div class="swiper-slide">
<img src="图片地址" alt="">
</div>
...
</div>
<div class="swiper-pagination"></div>
</div>
</template>
```
5.配置轮播图选项
```
new Swiper('.swiper-container', {
// 轮播图配置项
autoplay: true, // 自动播放
loop: true, // 循环播放
speed: 1000, // 切换速度
pagination: {
el: '.swiper-pagination', // 分页器容器
}
})
```
6.完整的组件代码示例
```
<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
<img src="图片地址" alt="">
</div>
<div class="swiper-slide">
<img src="图片地址" alt="">
</div>
...
</div>
<div class="swiper-pagination"></div>
</div>
</template>
<script>
import Swiper from 'swiper'
import 'swiper/dist/css/swiper.css'
export default {
mounted() {
new Swiper('.swiper-container', {
autoplay: true,
loop: true,
speed: 1000,
pagination: {
el: '.swiper-pagination',
}
})
}
}
</script>
<style scoped>
.swiper-container {
height: 400px;
}
.swiper-slide img {
width: 100%;
height: 100%;
}
</style>
```
阅读全文