1. 安裝vue-awesome-swiper
npm install vue-awesome-swiper@5.0.1 swiper --save
2. 組件引入方式
在Vue 3的<script setup>語(yǔ)法中引入組件:
// 導(dǎo)入Swiper和SwiperSlide組件
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
// 導(dǎo)入swiper的樣式文件
import 'swiper/swiper.scss';
3. 在模板中使用
<!-- 使用vue-awesome-swiper組件實(shí)現(xiàn)輪播效果 -->
<Swiper ref="swiper" :options="options">
<!-- 遍歷數(shù)據(jù),為每個(gè)數(shù)據(jù)項(xiàng)創(chuàng)建一個(gè)輪播滑塊 -->
<SwiperSlide v-for="(n, index) in (data || [])" :key="index">
<!-- 顯示圖片,并添加點(diǎn)擊事件 -->
<img :src="n.fileurl" @click="toTouziyouliao(n, index)">
</SwiperSlide>
</Swiper>
4. 配置選項(xiàng)
// 創(chuàng)建swiper的配置選項(xiàng)
const options = ref({
// 滑塊之間的間距(像素)
spaceBetween: 12,
// 滑塊尾部額外的空間
slidesOffsetAfter: 0,
// 設(shè)置為'auto'時(shí),根據(jù)滑塊寬度自動(dòng)調(diào)整顯示數(shù)量
slidesPerView: 'auto',
// 抵抗力比例,設(shè)為0表示無(wú)抵抗力
resistanceRatio: '0',
// 自由模式,允許滑塊自由滑動(dòng),不會(huì)自動(dòng)吸附到特定位置
freeMode: true
})
5. 創(chuàng)建組件引用
// 創(chuàng)建對(duì)swiper實(shí)例的引用
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) {
// 處理點(diǎn)擊事件邏輯
// 例如頁(yè)面跳轉(zhuǎn)、數(shù)據(jù)統(tǒng)計(jì)等
}