[Vuejs]-How to make pause/continue button for swiper

1👍

You can combine start/stop functions in one and use data property to decide which one to run:

const app = Vue.createApp({
  data() {
    return {
      swiperState: 'continue'
    }
  },
  methods: {
    swiperAction() {
      if(this.swiperState === 'continue') {
        this.swiperState = 'pause'
        //this.swiper.autoplay.start()
      } else {
        this.swiperState = 'continue'
        //this.swiper.autoplay.stop();
      }
    },
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="flex gap-2">
     <button @click="swiperAction">{{ swiperState }}</button>
    </div>
</div>

0👍

Final Ans (Solved):

Follow Nikola Pavicevic’s sample, set a default value is play and v-on the check the state(play/stop). Then change the state when button is pressed and execute stop() or start().

Template:

<button @click="swiperAction">
  <div v-if="swiperState === 'play'">
    <img src="src/image/button/pause.png" />
  </div>

  <div v-if="swiperState === 'stop'">
    <img class="scale-150" src="src/image/button/play.png" />
  </div>
</button>

Script:

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  setup() {
    /* Swiper Img */
    const shows = ref([
      { image: "src/image/swiper-1/show1.jpg" },
      { image: "src/image/swiper-1/show2.jpg" },
      { image: "src/image/swiper-1/show3.jpg" },
    ]);
    return {
      modules: [Autoplay, Pagination, Navigation],
      shows,
    };
  },
  data() {
    return {
      swiperState: "play",
    };
  },
  methods: {
    onSwiper(sw) {
      this.swiper = sw;
    },
    // Switch play & pause
    swiperAction() {
      if (this.swiperState === "play") {
        this.swiperState = "pause";
        this.swiper.autoplay.stop();
      } else {
        this.swiperState = "play";
        this.swiper.autoplay.start();
      }
    },
  },
};

Leave a comment