Lala的前端大補帖

歡迎一起鑽研前端技術😊

0%

Solved-swiper.slideTo is not a function

swiper

在製作 Swiper 輪播時,我希望 mouseenter 到 thumb 時,就會指定到該 slide
但卻出現了以下錯誤:
Uncaught TypeError: imagesSwiper.value.slideTo is not a function
*版本 vue: ^3.3.4 / swiper: ^11.0.3


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<script setup>
import { Swiper, SwiperSlide } from "swiper/vue";
import { Navigation, Autoplay, Thumbs, EffectCoverflow } from "swiper/modules";
import "swiper/css";
import "swiper/css/thumbs";

const modules = [Navigation, Autoplay, Thumbs, EffectCoverflow];
const data = reactive({
data: [
{
image: Image1,
title: "data1",
},
{
image: Image2,
title: "data2",
},
{
image: Image3,
title: "data3",
},
],
});

const thumbsSwiper = ref(null);
const imagesSwiper = ref(null);

const setThumbsSwiper = (swiper) => {
thumbsSwiper.value = swiper;
};

const setImageSwiper = (swiper) => {
imagesSwiper.value = swiper;
};

const changeSlide = (idx) => {
imagesSwiper.value.slideTo(idx);
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
<swiper
:modules="modules"
:slides-per-view="3"
:direction="'vertical'"
:spaceBetween="40"
watch-slides-progress
@swiper="setThumbsSwiper"
>
<swiper-slide
v-for="(item, idx) in data.data"
:key="item.title"
@mouseenter="changeSlide(idx)"
>
<div>
{{ item.title }}
</div>
</swiper-slide>
</swiper>

<swiper
:modules="modules"
:effect="'coverflow'"
:direction="'vertical'"
:speed="1000"
:coverflow-effect="{
rotate: 0,
stretch: -300, // 每個slide之間拉伸值(負值遠離)
depth: 300, // 值越大圖片越往後退
modifier: 1,
slideShadows: false,
}"
:thumbs="{ swiper: thumbsSwiper }"
@swiper="setImageSwiper"
ref="imagesSwiper"
>
<swiper-slide v-for="item in data.data" :key="item.title">
<div>
<img :src="item.image"/>
</div>
</swiper-slide>
</swiper>
</template>


解譯bug

Uncaught TypeError: imagesSwiper.value.slideTo is not a function
在 imagesSwiper.value 找不到 slideTo 的 function



錯誤原因

用了 ref 想綁定 imagesSwiper,但這抓到的是整個 swiper 的 HTML 區塊,所以不會有 slideTo 的 function
應使用 @swiper=”setImageSwiper” 來綁定 swiper 實體才能使用 slideTo function

1
2
3
const setImageSwiper = (swiper) => {
imagesSwiper.value = swiper;
};


如何解決

因為本來就已經有設定 @swiper=”setImageSwiper”,把 ref=”imagesSwiper” 拿掉就可以抓到 swiper 了



🚀線上課程分享

線上課程可以加速學習的時間,省去了不少看文件的時間XD,以下是我推薦的一些課程
想學習更多關於前後端的線上課程,可以參考看看。

Hahow

Hahow 有各式各樣類型的課程,而且是無限次數觀看,對學生或上班族而言,不用擔心被時間綁住



六角學院

如果你是初學者,非常推薦六角學院哦!
剛開始轉職也是上了六角的課,非常的淺顯易懂,最重要的是,隨時還有線上的助教幫你解決問題!


Udemy

Udemy 裡的課程非常的多,品質普遍不錯,且價格都滿實惠的,CP值很高!
也是很多工程師推薦的線上課程網站。
❤️