前言
在實際運用swiper輪播圖插件時,有時會出現(xiàn)需要同時使用 loop: true
和 slidesPerView: ‘a(chǎn)uto’
兩種屬性的情況,前者代表開啟循環(huán)模式,后者代表slider容器能夠同時顯示的slides數(shù)量(carousel模式)。
此時,會出現(xiàn)點擊事件失效問題,主要原因是 loop: true
會產(chǎn)生復制的slide,而在“假的”slide上正常綁定的點擊事件無法生效。
一、swiper - loop原理
參考鏈接:Swiper中文網(wǎng) - loop
二、swiper - slidesPerView屬性解釋
參考鏈接:Swiper中文網(wǎng) - carousel文章來源:http://www.zghlxwxcb.cn/news/detail-469352.html
三、解決方法
1. HTML部分
<div class="carousel">
<swiper ref="noticeSwiper" :options="swiperOptions">
<swiper-slide v-for="(item, i) in list.notice" :key="i">
<div class="title">
<span>{{ item.title }}</span>
</div>
<span>{{ item.createdTime }}</span>
</swiper-slide>
</swiper>
</div>
2. data部分
let vm = null
export default {
// etc.
}
data() {
return {
list: {
notice: [], // 列表
}
swiperOptions: {
direction: 'vertical',
height: 52,
slidesPerView: 2,
loopedSlides: 4, // 在loop模式下使用slidesPerView,還需使用該參數(shù)設置所要用到的loop個數(shù)(一般設置大于可視slide個數(shù)2個即可)
observer: true, // 改變swiper樣式時,自動初始化swiper
observeParents: true, // 監(jiān)測swiper父元素,如果有變化則初始化swiper
autoplay: {
delay: 3000,
disableOnInteraction: false,
},
loop: true,
on: {
tap: function () {
// 這里有坑,需要注意的是:
// this 指向的是 swpier 實例,而不是當前的 vue, 因此借助 vm,來調(diào)用 methods 里的方法
let initIndex = this.clickedIndex - this.activeIndex + this.realIndex
let index = initIndex === vm.list.notice.length ? 0 : initIndex
vm.toNoticeDetail(index)
},
},
}
}
}
computed: {
noticeSwiper() {
return this.$refs.noticeSwiper.$swiper
},
}
3. 方法部分
methods: {
toNoticeDetail(index) {
// 示例:查看詳情
this.$router.push({
path: '/contentDetail',
query: {
id: this.list.notice[index].id, // 通過index獲取數(shù)據(jù)
},
})
},
}
created () {
vm = this
}
總結(jié)
在vue中使用swiper,同時設置loop和slidesPerView時,解決點擊事件失效問題的關(guān)鍵,在于獲取真實的 index
以及設置 loopedSlides
屬性。文章來源地址http://www.zghlxwxcb.cn/news/detail-469352.html
到了這里,關(guān)于解決vue中使用swiper 同時設置loop和slidesPerView時 點擊事件失效問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!