记一次Vue3中使用vue-awesome-swiper遇到的坑
目录
- 记一次Vue3中使用vue-awesome-swiper遇到的坑
- 问题现象
记一次Vue3中使用vue-awesome-swiper遇到的坑
在最近的Vue2组件切换到Vue3时,发现了 vue-awesome-swiper版本V5.0.1 的一处坑。记录一下,希望对大家有所帮助。
问题现象
<template>
...
<swiper
class="swiper"
:activeIndex="state.activePosterIndex"
:options="state.swiperOptions"
@slide-change="handlePosterChange"
ref="mySwiperRef"
>
<swiper-slide v-for="(item, index) in state.detailItemCodesList" :key="index">
<div class="swiper-item">
<a-image style="width: 300px; height: 300px" :src="item.previewUrl" />
</div>
</swiper-slide>
</swiper>
<div
v-for="(item, index) in state.detailItemCodesList"
:key="index"
:class="['poster', state.activePosterIndex === index ? 'active' : '']"
@click="handlePosterClick(index)"
>
<img style="width: 120px; height: 120px" fit="fill" :src="item.previewUrl" />
<div class="poster-code">{{ item.itemCode }}</div>
</div>
...
</template>
<script setup lang="ts">
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import type { Swiper as SwiperClass } from 'swiper/types'
const mySwiperRef = ref<SwiperClass>()
// 监听封面图点击
const handlePosterClick = (index) => {
state.activePosterIndex = index
console.log('mySwiperRef.value---', mySwiperRef.value)
mySwiperRef.value.slideTo(state.activePosterIndex, 500, false)
}
</script>
主要逻辑是这样的:
- 顶部一个Swiper组件,下面一个缩略图;
- 滑动Swiper切换缩略图的选中状态;
- 选中不同缩略图切换到对应Swiper下标。
但是在点击缩略图切换Swiper下标时一直提示slideTo
未定义 ,打印mySwiperRef.value
也确实发现里面没有slideTo
方法。后来查看文档(https://swiperjs.com/swiper-api)确实是有此方法,再多次搜索相关文章,终于在别人的示例代码中查到了蛛丝马迹:在标签上不需要使用ref
,mySwiperRef.value
的赋值需要在swiper
回调中,更改后的代码如下:
<template>
...
<swiper
class="swiper"
:activeIndex="state.activePosterIndex"
:options="state.swiperOptions"
@slide-change="handlePosterChange"
- ref="mySwiperRef"
+ @swiper="onSwiper"
>
<swiper-slide v-for="(item, index) in state.detailItemCodesList" :key="index">
<div class="swiper-item">
<a-image style="width: 300px; height: 300px" :src="item.previewUrl" />
</div>
</swiper-slide>
</swiper>
<div
v-for="(item, index) in state.detailItemCodesList"
:key="index"
:class="['poster', state.activePosterIndex === index ? 'active' : '']"
@click="handlePosterClick(index)"
>
<img style="width: 120px; height: 120px" fit="fill" :src="item.previewUrl" />
<div class="poster-code">{{ item.itemCode }}</div>
</div>
...
</template>
<script setup lang="ts">
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import type { Swiper as SwiperClass } from 'swiper/types'
const mySwiperRef = ref<SwiperClass>()
+ const onSwiper = (swiper: SwiperClass) => {
+ mySwiperRef.value = swiper
+ console.log('mySwiperRef.value---', mySwiperRef.value)
+ }
// 监听封面图点击
const handlePosterClick = (index) => {
state.activePosterIndex = index
console.log('mySwiperRef.value---', mySwiperRef.value)
mySwiperRef.value.slideTo(state.activePosterIndex, 500, false)
}
</script>