vue2项目最好不要用swiper的最新版本,不兼容。
npm i swiper@5 --save
import Swiper from 'swiper'
因为不知一处用到轮播图,直接在入口文件引入一次即可。
import "swiper/css/swiper.css"
new Swiper ('.swiper-container', {
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable :true
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
// 如果需要滚动条
scrollbar: {
el: '.swiper-scrollbar',
},
})
因为在运行swiper实例之前,它的页面结构必须以及存在且完整,而此时由于轮播图的数据需要从store仓库中获得需要花费时间,所以此时的页面结构是不完整的,所以在mounted中书写没有效果。
在mounted中使用setTimeout来实现过一段时间后执行,可以解决这个问题,但是不完美。
setTimeout(()=>{
new Swiper ('.swiper-container', {
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable :true
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
// 如果需要滚动条
scrollbar: {
el: '.swiper-scrollbar',
},
})
},1000)
监听bannerList数据的变化,只要state中从空数组变为非空数组就能监听到
但是这个只能保证bannerList的数据以及有了,不能保证页面组件中的v-for以及循环结束,所以还需要nectTick。
定义:在下次DOM更新循环结束之后执行延迟回调,在修改数据之后,立即使用这个方法,获取更新后的DOM。
同时满足两个“之后”才执行。它保证了页面中的结构一定存在且完整
所以最终的watch+nectTick组合使用才能实现轮播图的最佳效果。
watch:{
bannerList:{
handler(){
this.$nextTick(()=>{
new Swiper ('.swiper-container', {
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable :true
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
// 如果需要滚动条
scrollbar: {
el: '.swiper-scrollbar',
},
})
})
}
}
}