Search code examples
vue.jsvuejs3swiper.js

How to use Swiper slideTo() in Vue3.0?


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


Solution

  • 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).