开启loop后dom复制问题
1.给标签添加事件触发不了
- 是因为开启loop后dom复制问题,只复制了dom结构未复制添加的事件
解决方法
- 使用H5中的自定义属性 data-index 添加为当前的index值,再给需要点击的标签一个唯一的标识,我这边用的是class加了唯一标识
<swiper ref="mySwiper"
:options="swiperOptions" v-if="dataList" :key="key">
<template v-for="(item, index) in dataList">
<swiper-slide
:key="index"
:style="swiperStyle">
<div class="left-img">
<div :style="leftImgStyle(item.imgUrl)"></div>
</div>
<div class="right-text">
<table>
<tr>
<td>
<label class="key">姓名:</label>
</td>
<td class="name" :data-index="index">{{item.name || '暂无数据'}}</td>
</tr>
</table>
</div>
</swiper-slide>
</template>
</swiper>
- 配置项写入computed中,在swiper中的on中添加点击事件,通过事件对象参数 中的 target 为真正的触发者,然后根据上面html添加的唯一标识来触发不同的事件函数即可, ⚠️ on对象中的this为 Swiper 实例,所以需要将 当前组件的实例挂载到变量上。
swiperOptions () {
let vm = this
const { data, config: { swiper: { atuoplay, delay, slidesPerView, spaceBetween } } } = this
return {
pagination: {
el: '.swiper-pagination'
},
// init:false,
loop : data.length <= slidesPerView ? false : true,
direction: 'vertical',
slidesPerView,
autoplay: atuoplay ? {
delay,
disableOnInteraction: false
} : undefined,
observer: true,
observeParents: true,
observeSlideChildren: true,
spaceBetween: slidesPerView > 1 ? spaceBetween : 0,
debugger: true,
on: {
click (e) {
// const realIndex = this.realIndex;
if (e.target.className == "idCard") {
vm.idCardClick(e.target.dataset.index);
} else if (e.target.className == "warning") {
vm.warningClick(e.target.dataset.index)
}
// console.log(vm);
// vm.handleClickSlide(realIndex)
}
}
}
},
2.实时修改options配置问题
- vue-awesome-swiper并没有对options的配置项进行监听,所以当有时候改变options值想要改变样式并未能实现
解决方法
- 监听数据变化和options的变化进行 key 值的重新赋值(我是使用uuid进行赋值),这样可以是的Vue视图进行强制刷新(不推荐)
<swiper ref="mySwiper"
:options="swiperOptions" v-if="dataList" :key="key">
</swiper>
出现的问题
这样解决是使得每次options发生改变或数据发生改变swiper都会重新渲染,而且使得swiper实例为被销毁状态 destroyed:true。 所以当我想要在这种情况下调用到swiper中的内置方法是调用不到的
出现场景
当开启loop=true时,希望鼠标hover进去后轮播暂停,离开后继续轮播
// 给外面盒子加鼠标进入事件和鼠标离开事件
<div @mouseenter="stopSwiper" @mouseleave="runSwiper"></div>
//
stopSwiper () {
// this.$refs.mySwiper?.$swiper.autoplay.stop();
this.$refs.mySwiper.swiperInstance.autoplay.stop()
},
runSwiper () {
// this.$refs.mySwiper?.$swiper.autoplay.start();
this.$refs.mySwiper.swiperInstance.autoplay.start()
},
刚开始想要用 Swiper 实例调取方法去控制轮播的开始和停止,但是我用了这种方法后swiper是被销毁掉的,但是Swiper会实例化出一个 swiperInstance 而不会被销毁,里面的方法也可以被调用,就解决了 Swiper被销毁的问题
- 通过 parmas 进行直接赋值 (个人感觉不怎么好用,但是改一些简单的配置还是很不错的)
// computed中
swiper() {
return this.$refs.mySwiper?.$swiper
},
// 需要改变的函数中
this.swiper.params.autoplay=200;
3.slidesPerView的数量大于展示数据时,开启loop复制问题
- slidesPerView的数量大于展示数据时,开启loop会复制出dom,导致会出现两个相同的dom
解决方法
因为我的options时写在computd中的,而且每次改变后重新刷新dom渲染,所以只需要判断 slidesPerView 和 data 的数量比较,来控制 loop的 开关
// computd
swiperOptions () {
const { data, config: { swiper: { atuoplay, delay, slidesPerView, spaceBetween } } } = this
return {
loop : data.length <= slidesPerView ? false : true,
slidesPerView,
},
vue-awesome-swiper 在使用过程中真的踩了太多坑了,希望记录一下能够帮助到需要的人