1. 安装vue-awesome-swiper
npm install vue-awesome-swiper@5.0.1 swiper --save
2. 组件引入方式
在Vue 3的<script setup>语法中引入组件:
// 导入Swiper和SwiperSlide组件
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
// 导入swiper的样式文件
import 'swiper/swiper.scss';
3. 在模板中使用
<!-- 使用vue-awesome-swiper组件实现轮播效果 -->
<Swiper ref="swiper" :options="options">
<!-- 遍历数据,为每个数据项创建一个轮播滑块 -->
<SwiperSlide v-for="(n, index) in (data || [])" :key="index">
<!-- 显示图片,并添加点击事件 -->
<img :src="n.fileurl" @click="toTouziyouliao(n, index)">
</SwiperSlide>
</Swiper>
4. 配置选项
// 创建swiper的配置选项
const options = ref({
// 滑块之间的间距(像素)
spaceBetween: 12,
// 滑块尾部额外的空间
slidesOffsetAfter: 0,
// 设置为'auto'时,根据滑块宽度自动调整显示数量
slidesPerView: 'auto',
// 抵抗力比例,设为0表示无抵抗力
resistanceRatio: '0',
// 自由模式,允许滑块自由滑动,不会自动吸附到特定位置
freeMode: true
})
5. 创建组件引用
// 创建对swiper实例的引用
const swiper = ref(null)
6. 添加样式
/* 轮播容器样式 */
.container {
padding: 0 10px 15px 10px;
}
/* 轮播滑块样式 */
.swiper-slide {
width: 140px;
height: 160px;
img {
height: 100%;
width: 100%;
display: block;
border-radius: 8px;
}
}
7. 事件处理
function handleClick(item) {
// 处理点击事件逻辑
// 例如页面跳转、数据统计等
}