vue3切换页面路由再返回swiper失效
问题描述:在vue3项目使用swiper插件时,进入页面swiper轮播图能正常运行,但是在切换了页面再返回有轮播的页面,轮播图就停留在第一张, 并且轮播进度指示点只有一个。
出现问题的代码
<div class="swiper-container swiper">
<div class="swiper-wrapper">
<div class="swiper-slide main-list list-01" :style="backgroundDiv0">
<img v-if="!isLoading" class="list-01-img" src="" alt="">
</div>
<div class="swiper-slide main-list list-02" :style="backgroundDiv4"></div>
</div>
<div class="swiper-pagination"></div>
</div>
<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
export default defineComponent({
setup() {
mySwiper = new Swiper(".swiper-container", {
watchSlidesProgress: true,
slidesPerView: 'auto',
centeredSlides: true,
loop: true,
loopedSlides: 14,
autoplay: {
delay: 3000,
disableOnInteraction: false,
},
pagination: {
el: '.swiper-pagination',
type: 'bullets',
clickable: true
}
})
}
})
</script>
问题解决
给swiper的方法加上定时器, 在onMounted中执行
<script lang="ts">
import { defineComponent} from 'vue'
export default defineComponent({
setup() {
let mySwiper = null
const initSlider = async () => {
await nextTick()
const timer = setTimeout(()=> {
mySwiper = new Swiper(".swiper-container", {
watchSlidesProgress: true,
slidesPerView: 'auto',
centeredSlides: true,
loop: true,
loopedSlides: 14,
autoplay: {
delay: 3000,
disableOnInteraction: false,
},
pagination: {
el: '.swiper-pagination',
type: 'bullets',
clickable: true
}
});
clearTimeout(timer) // 清除定时器
}, 400)
}
onMounted( () => {
initSlider()
})
return {
}
}
})
</script>
end 用完定时器记得清除
版权声明:本文为qq_41421033原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。