场景:banner 用插件vue-awesome-swiper实现,loop属性为true,那么会有节点被复制,那么被复制的节点没有绑定点击事件
通过 swiper 强大的 api 文档,解决了上述出现的问题。关键点在于:
- 当 loop 设置为 true 的时候,不能再用 activeIndex 或者 clickedIndex。只能用realIndex。官方的解释为:当前活动块的索引,与activeIndex不同的是,在loop模式下不会将复制的块的数量计算在内。
- 点击事件不能绑定在 dom 上
解决方法:
html代码
<div v-if="bannerList && bannerList.length > 1" class="banner parent-banner">
<swiper :options="swiperOption">
<swiper-slide v-for="(item, i) in bannerList" :key="i">
<div class="banner-img">
<img :src="item.image | handleResourcePrefix" alt>
</div>
<div class="banner-shadow"></div>
</swiper-slide>
</swiper>
<div class="swiper-pagination banner-swiper-pagination" slot="pagination"></div>
</div>
js代码
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
let vm = null;
export default {
created () {
vm = this
this.fetchBanner()
},
data () {
return {
bannerList: [],
// 轮播配置项
swiperOption: {
notNextTick: true,
pagination: {
el: '.banner-swiper-pagination'
},
autoplay: {
stopOnLastSlide: false,
disableOnInteraction: false
},
delay: 1000,
loop: true,
on: {
click () {
// 这里有坑
// 需要注意的是:this 指向的是 swpier 实例,而不是当前的 vue, 因此借助 vm,来调用 methods 里的方法
// console.log(this); // -> Swiper
// 当前活动块的索引,与activeIndex不同的是,在loop模式下不会将 复制的块 的数量计算在内。
const realIndex = this.realIndex
vm.buriedPoint(vm.bannerList[realIndex])
}
}
}
}
}
components: {
swiper,
swiperSlide
},
methods: {
// 获取banner
fetchBanner () {
this.$http.get('v1/common/banner', {
params: {
banner_position_name: '首页顶部一',
type: 2
}
}).then(response => {
let data = response.data.meta
this.bannerList = data
}).catch(err => {
this.$utils.showErrorMsg(err)
})
},
// 广告埋点
buriedPoint (info) {
this.$ba && this.$ba.trackEvent('教师端首页顶部一', '点击', `${info.name}(${info.id})`)
let timer = setTimeout(() => {
location.href = info.url
clearTimeout(timer)
}, 100)
}
}
}