vue-awesome-swiper缩略图控制循环无效解决方案
在使用vue-awesome-swiper当中的Thumbs Gallery With Two-Way Control Loop ( 缩略图控制循环 )
时,官方示例的代码并不好用,不是出现bug就是缩略图只能居中,不能从左下角对齐
官方demo
<template>
<md-card>
...
</md-card-actions>
<md-card-media style="height: 500px">
<!-- swiper1 -->
<swiper :options="swiperOptionTop" class="gallery-top" ref="swiperTop">
<swiper-slide class="slide-1"></swiper-slide>
<swiper-slide class="slide-2"></swiper-slide>
<swiper-slide class="slide-3"></swiper-slide>
<swiper-slide class="slide-4"></swiper-slide>
<swiper-slide class="slide-5"></swiper-slide>
<div class="swiper-button-next swiper-button-white" slot="button-next"></div>
<div class="swiper-button-prev swiper-button-white" slot="button-prev"></div>
</swiper>
<!-- swiper2 Thumbs -->
<swiper :options="swiperOptionThumbs" class="gallery-thumbs" ref="swiperThumbs">
<swiper-slide class="slide-1"></swiper-slide>
<swiper-slide class="slide-2"></swiper-slide>
<swiper-slide class="slide-3"></swiper-slide>
<swiper-slide class="slide-4"></swiper-slide>
<swiper-slide class="slide-5"></swiper-slide>
</swiper>
</md-card-media>
</md-card>
</template>
<script>
export default {
data() {
return {
swiperOptionTop: {
spaceBetween: 10,
loop: true,
loopedSlides: 5, //looped slides should be the same
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
},
swiperOptionThumbs: {
spaceBetween: 10,
slidesPerView: 4,
touchRatio: 0.2,
loop: true,
loopedSlides: 5, //looped slides should be the same
slideToClickedSlide: true,
}
}
},
mounted() {
this.$nextTick(() => {
const swiperTop = this.$refs.swiperTop.swiper
const swiperThumbs = this.$refs.swiperThumbs.swiper
swiperTop.controller.control = swiperThumbs
swiperThumbs.controller.control = swiperTop
})
}
}
</script>
<style lang="scss" scoped>
...
</style>
遇到无限轮播无效问题
原因是没有对图片数据进行校验判断。
解决方法
<swiper :options="swiperOptionTop" class="gallery-top" ref="swiperTop" v-if="dataList.length > 0">
<swiper-slide v-for="(item,index) in dataList">
<img v-img:group class="comp-intro-banner"
:src="item.imgUrl" alt="item.title">
</swiper-slide>
<div class="swiper-button-next swiper-button-white" slot="button-next"></div>
<div class="swiper-button-prev swiper-button-white" slot="button-prev"></div>
</swiper>
这次图片可以轮播了。但是top和thumbs在变化时又出现了不同步的问题。
top和thumbs在变化时又出现了不同步的问题。
此时会在控制台报错找不到Controller,找不到swiper。
原因是mounted中找不到$ref.swiperTop.swiper
vue官网是这样说的
当 v-for 用于元素或组件的时候,引用信息将是包含 DOM 节点或组件实例的数组。
关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候你不能访问它们 - 它们还不存在!$refs 也不是响应式的,因此你不应该试图用它在模板中做数据绑定。
解决方法
updated替换mounted,但是这样每一次DOM结构更新,vue都会调用一次updated(){}钩子函数,而我们只需要在swiper初始化的时候进行调用。
updated () {
if (this.isInit === 1) {
this.$nextTick(() => {
const swiperTop = this.$refs.swiperTop.swiper
const swiperThumbs = this.$refs.swiperThumbs.swiper
console.log(this.$refs)
swiperTop.controller.control = swiperThumbs
swiperThumbs.controller.control = swiperTop
})
this.isInit = 0
}
},