Reputation: 33
Vue version:3.0.2
Swiper version:6.3.5
I'd like to use Swiper's slideTo method in Vue3.0, but it doesn't seem to work.
Can you tell me how to use it? https://codesandbox.io/s/interesting-hooks-1jblc?file=/src/App.vue
Upvotes: 3
Views: 13355
Reputation: 369
If you're using <script setup>
, you can do it like this:
<script setup>
import { ref } from 'vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
const swiperInstance = ref()
function onSwiper(swiper) {
swiperInstance.value = swiper
}
function goToSlide(position) {
swiperInstance.value?.slideTo(position)
}
</script>
<template>
<button @click="goToSlide(3)">
Go to slide 3
</button>
<Swiper @swiper="onSwiper">
<SwiperSlide v-for="i in 4">
Slide {{ i }}
</SwiperSlide>
</Swiper>
</template>
Upvotes: 6
Reputation: 11
<template>
<button @click="slideToIndex(3)">
Go to slide 3
</button>
<Swiper @swiper="onSwiper">
<SwiperSlide v-for="i in 4">
Slide {{ i }}
</SwiperSlide>
</Swiper>
</template>
<script setup>
import { ref } from 'vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
const swiperInstance = ref()
onSwiper = (swiper) =>{
swiperInstance.value = swiper
}
slideToIndex = (index) =>{
swiperInstance.value.slideTo(index)
}
</script>
Upvotes: 1
Reputation: 9190
You seem to be using one library but referring to the other for documentations.
You are importing the library from swiper/vue
, so it has to be the official one; in which case, there is a slight difference in accessing the Swiper instance: You need to store the Swiper instance. (see Controller mode). So in your case:
<template>
<swiper
style="border: 1px solid red; width: 400px"
:slides-per-view="1"
@swiper="onSwiper"
>
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
<swiper-slide>Slide 3</swiper-slide>
<swiper-slide>Slide 4</swiper-slide>
</swiper>
<button @click="handleSlideTo">slide to 4</button>
</template>
<script>
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";
export default {
name: "App",
components: {
Swiper,
SwiperSlide,
},
data() {
return {
swiper: null,
};
},
methods: {
onSwiper(swiper) {
this.swiper = swiper;
},
handleSlideTo() {
this.swiper.slideTo(3);
},
},
};
</script>
Not to be confused with the use of ref
by the other library (vue-awesome-swiper
).
Upvotes: 18