vue使用swiper插件心得体会
swiper使用步骤
1. 通过npm安装相应版本的swiper插件(这里使用5.4.5)最新的稳定版本
npm install swiper@5.4.5 --save
2. 导入js/css
局部导入
import Swiper from 'swiper'
import 'swiper/css/swiper.min.css'
3. html部分代码
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(item,index) in banners" :key="index">
<img :src="item.image" alt="">
</div>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
</div>
4. 在组件挂载到dom上的时候初始化swiper
mounted(){
const mySwiper = new Swiper('.swiper-container',{
loop:true,//是否循环轮播
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
},
})
}
5. 设置完成以后我们会发现轮播图无法正常显示,这是由于我这里在组件创建时获取数据并渲染,而Swiper是在组件挂载到dom上时才初始化,这就可能导致Swiper初始化完成后,页面还没渲染完毕.因此我们需要在实例化Swiper中添加配置observer:true,observeParents:true,以此来让Swiper内容改变时自动初始化。
更改后的实例化对象:
6. 刷新页面发现另一个问题,loop循环轮播的效果并没有起作用
后来发现需要在使用该组件的时候进行数据判断
重新刷新页面,发现轮播图可以正常使用
Swiper的详细使用见官网:https://www.swiper.com.cn/