特点
该方案可以捕捉到swiper单屏内点击不同元素的事件。常用方式使用swiper只能说判断到点击了第几屏,并不能判断点击了第几屏里的哪一个元素并传递数据触发对应事件执行。特别是首屏,因为第一屏的结构是swiper复制多出的一屏没有绑定click的方法。(此处特指循环轮播的swiper)
效果
image.png代码
<template>
<!-- E网点 -->
<div class="test">
<!-- 详情内容 -->
<div class="ads-swiper-box"
v-if="swiperOption">
<swiper :options="swiperOption"
class="swiper-container"
v-if="list.length>0">
<!-- slides -->
<swiper-slide class="swiper-item"
v-for="(item,index) in list"
:key="index"
:style="'height:120px;width:100%;background-color:'+item.bgc+';'"
data-clickmehtod="clickSlide">
<div data-clickmehtod="handleEvent1"
class="btn">按钮1</div>
<div data-clickmehtod="handleEvent2"
class="btn">按钮2</div>
<div data-clickmehtod="handleEvent3"
class="btn">按钮3</div>
</swiper-slide>
<div class="swiper-pagination"
slot="pagination"></div>
</swiper>
</div>
</div>
</template>
<script>
export default {
data () {
return {
list: [{ 'bgc': 'red' }, { 'bgc': 'yellow' }, { 'bgc': 'green' }],
swiperOption: null
};
},
mounted () {
var that = this
that.swiperOption = {
pagination: {
el: ".swiper-pagination"
},
slidesPerView: 1,
autoplay: {
delay: 3000,
disableOnInteraction: false
},
spaceBetween: 30,
loop: true,
on: {
click: function (e) {//此处不能为箭头函数,保证函数内this指向swiper
// this.realIndex 获取真正的屏页索引
var realIdx = this.realIndex
var item = that.list[realIdx]
// 获取属性绑定的函数名
var fn = that[e.target.dataset.clickmehtod]
if (fn && typeof fn === 'function') {
fn(item,realIdx)
}
}
}
}
},
methods: {
clickSlide (item,realIdx) {
// 点击第realIdx屏,数据item
console.log('clickSlide', item);
},
handleEvent1 (item,realIdx) {
// 点击第realIdx屏的按钮1,数据item
console.log('handleEvent1', item);
},
handleEvent2 (item,realIdx) {
// 点击第realIdx屏的按钮2,数据item
console.log('handleEvent2', item);
},
handleEvent3 (item,realIdx) {
// 点击第realIdx屏的按钮3,数据item
console.log('handleEvent3', item);
}
}
};
</script>
<style lang="scss" scoped>
.btn {
margin: 0 auto;
height: 40px;
width: 80px;
line-height: 40px;
border: 1px solid #333;
}
</style>
网友评论