Vue中使用Swiper简单封装组件示例
作者:黄金原野
这篇文章主要为大家介绍了Vue中使用Swiper简单封装组件示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
正文
Swiper的最简单使用,参考官网教程
但通常情况下,<swiper-slide></swiper-slide>作为循环展示的内容,需要能够展示多种样式的循环列表,此时必须要使用slot
需要封装的Swiper组件命名为MySwiper.vue,代码如下
loop表示是否循环展示,值为false时会来回切换,相当魔性autoplay是否自动循环展示,值为false时不会自动循环,delay为每页停留的时间
需要循环的部分<swiper-slide>,其中应当包含的内容就是需要循环展示的自定义组件,使用slot插槽占位
在调用时,首先从父组件获取数据showList,传至子组件MySwiper,MySwiper中<swiper-slide>循环若干次,也就生成了若干的slot,在调用slot的时候,绑定名为item的attribute,在父组件中可以通过v-slot接受,参数起名为slotProps,b包含所有slot中传输的attribute,此处包含传输的item。
作用域插槽
<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的设置。<swiper-slide>中,如果直接写html内容,例如div之流,swiper-slide的高度可以被正常撑开。但如果写成一个封装组件,swiper-slide的高度会渲染为0,导致内容显示为空。
此处有两个解决方案:
- 设置
swiper-slide的高度。虽然可以解决,但通用性较差,如果能确保所有Swiper高度相同,可以考虑。但需要注意min-height是无效的,不会随着填充的内容高度增加而增加,相当于是一个固定值 - 将父元素逐个设置为100%,虽然有点傻,但能较好地适应
Swiper中内容高度不同的情况
.swiper-display {
width: 100%;
height: 100%;
position: relative;
.swiper {
height: 100%;
.swiper-wrapper {
height: 100%;
.swiper-item {
height: 100%;
}
}
}以上就是Vue中使用Swiper简单封装组件示例的详细内容,更多关于Vue Swiper封装组件的资料请关注脚本之家其它相关文章!
