Vue中使用Swiper簡單封裝組件示例
正文
Swiper的最簡單使用,參考官網(wǎng)教程
但通常情況下,<swiper-slide></swiper-slide>作為循環(huán)展示的內(nèi)容,需要能夠展示多種樣式的循環(huán)列表,此時必須要使用slot
需要封裝的Swiper組件命名為MySwiper.vue,代碼如下
loop表示是否循環(huán)展示,值為false時會來回切換,相當(dāng)魔性autoplay是否自動循環(huán)展示,值為false時不會自動循環(huán),delay為每頁停留的時間
需要循環(huán)的部分<swiper-slide>,其中應(yīng)當(dāng)包含的內(nèi)容就是需要循環(huán)展示的自定義組件,使用slot插槽占位
在調(diào)用時,首先從父組件獲取數(shù)據(jù)showList,傳至子組件MySwiper,MySwiper中<swiper-slide>循環(huán)若干次,也就生成了若干的slot,在調(diào)用slot的時候,綁定名為item的attribute,在父組件中可以通過v-slot接受,參數(shù)起名為slotProps,b包含所有slot中傳輸?shù)腶ttribute,此處包含傳輸?shù)膇tem。
作用域插槽
<template>
<div class="swiper-display">
<swiper
:modules="modules"
:slides-per-view="1"
:space-between="50"
navigation
:pagination="{ clickable: true }"
:scrollbar="{ draggable: true }"
@swiper="onSwiper"
@slideChange="onSlideChange"
loop
autoplay="{
delay: 2000
}"
>
<swiper-slide class="swiper-item" v-for="item in list" :key="item.seq">
<slot :item="item"></slot>
</swiper-slide>
</swiper>
</div>
</template>
<script>
import { Navigation, Pagination, Scrollbar, A11y, Autoplay } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { onMounted } from 'vue';
import 'swiper/css';
export default {
components: {
Swiper,
SwiperSlide,
},
props: {
list: Array
},
setup(props) {
const onSwiper = (swiper) => {
// console.log(swiper);
};
const onSlideChange = () => {
// console.log('slide change');
};
return {
onSwiper,
onSlideChange,
modules: [Navigation, Pagination, Scrollbar, A11y, Autoplay],
autoPlay
};
},
}
</script>
<style lang="scss">
.swiper-display {
width: 100%;
height: 100%;
position: relative;
.swiper {
height: 100%;
.swiper-wrapper {
height: 100%;
.swiper-item {
height: 100%;
}
}
}
}
</style>使用方式如下,其中ToDisplay表示需要利用Swiper展示的自定義組件
<MySwiper v-slot="slotProps" :list="showList"> <ToDisplay :item="slotProps.item"></ToDisplay> </MySwiper>
此外,需要注意css的設(shè)置。<swiper-slide>中,如果直接寫html內(nèi)容,例如div之流,swiper-slide的高度可以被正常撐開。但如果寫成一個封裝組件,swiper-slide的高度會渲染為0,導(dǎo)致內(nèi)容顯示為空。
此處有兩個解決方案:
- 設(shè)置
swiper-slide的高度。雖然可以解決,但通用性較差,如果能確保所有Swiper高度相同,可以考慮。但需要注意min-height是無效的,不會隨著填充的內(nèi)容高度增加而增加,相當(dāng)于是一個固定值 - 將父元素逐個設(shè)置為100%,雖然有點傻,但能較好地適應(yīng)
Swiper中內(nèi)容高度不同的情況
.swiper-display {
width: 100%;
height: 100%;
position: relative;
.swiper {
height: 100%;
.swiper-wrapper {
height: 100%;
.swiper-item {
height: 100%;
}
}
}以上就是Vue中使用Swiper簡單封裝組件示例的詳細(xì)內(nèi)容,更多關(guān)于Vue Swiper封裝組件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Element-UI組件實現(xiàn)面包屑導(dǎo)航欄的示例代碼
面包屑導(dǎo)航欄是一種用戶界面組件,用于展示用戶在網(wǎng)站或應(yīng)用中的路徑,它包括了從主頁到當(dāng)前頁面的鏈接序列,有助于用戶快速了解和導(dǎo)航至上級頁面,本文就來介紹一下Element-UI組件實現(xiàn)面包屑導(dǎo)航欄的示例代碼,感興趣的可以了解一下2024-09-09

