特點(diǎn)
該方案可以捕捉到swiper單屏內(nèi)點(diǎn)擊不同元素的事件卑吭。常用方式使用swiper只能說(shuō)判斷到點(diǎn)擊了第幾屏芽淡,并不能判斷點(diǎn)擊了第幾屏里的哪一個(gè)元素并傳遞數(shù)據(jù)觸發(fā)對(duì)應(yīng)事件執(zhí)行。特別是首屏陨簇,因?yàn)榈谝黄恋慕Y(jié)構(gòu)是swiper復(fù)制多出的一屏沒(méi)有綁定click的方法吐绵。(此處特指循環(huán)輪播的swiper)
效果
image.png
代碼
<template>
<!-- E網(wǎng)點(diǎn) -->
<div class="test">
<!-- 詳情內(nèi)容 -->
<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) {//此處不能為箭頭函數(shù),保證函數(shù)內(nèi)this指向swiper
// this.realIndex 獲取真正的屏頁(yè)索引
var realIdx = this.realIndex
var item = that.list[realIdx]
// 獲取屬性綁定的函數(shù)名
var fn = that[e.target.dataset.clickmehtod]
if (fn && typeof fn === 'function') {
fn(item,realIdx)
}
}
}
}
},
methods: {
clickSlide (item,realIdx) {
// 點(diǎn)擊第realIdx屏河绽,數(shù)據(jù)item
console.log('clickSlide', item);
},
handleEvent1 (item,realIdx) {
// 點(diǎn)擊第realIdx屏的按鈕1己单,數(shù)據(jù)item
console.log('handleEvent1', item);
},
handleEvent2 (item,realIdx) {
// 點(diǎn)擊第realIdx屏的按鈕2,數(shù)據(jù)item
console.log('handleEvent2', item);
},
handleEvent3 (item,realIdx) {
// 點(diǎn)擊第realIdx屏的按鈕3耙饰,數(shù)據(jù)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>