[Vuejs]-How to stop autoplay in swiper immediately on hover

1👍

Since I didn’t find any answer, and no one gave any advice, I had to somehow get out of my way and I didn’t think of anything better than to do this scrolling myself

stopAutoplay() {
      if (this.swiper) {
        clearInterval(this.interval)
      }
    },
    startAutoplay() {
      const slideCount = this.swiper.slidesGrid.length
      this.interval = setInterval(() => {
        this.translate = this.translate + 30
        if (this.translate > this.swiper.slidesGrid[slideCount - 3]) {
          this.translate = this.swiper.slidesGrid[0]
        }
        this.$refs.wrapper.style = `transform: translate3d(-${this.translate}px, 0px, 0px)`

      }, 500)
    },

I just add an interval, and every half a second I move the block by a couple of pixels, and if I need to stop scrolling, I remove the interval

it’s not perfect, so if you have ideas on how to improve, please write

1👍

Try this

<template>
  <div
    class="swiper-brand-container"
    @mouseenter="stopAutoplay"
    @mouseleave="startAutoplay"
  >
    <!-- Your Swiper content goes here -->
  </div>
</template>

Or this

<template>
  <div
    class="swiper-brand-container"
    @mouseenter="freezeSlider"
    @mouseleave="unfreezeSlider"
  >
    <!-- Your Swiper content goes here -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      swiper: null,
      isFrozen: false,
    };
  },
  mounted() {
    this.initSwiper();
  },
  methods: {
    initSwiper() {
      this.swiper = new Swiper('.swiper-brand-container', {
        loop: true,
        spaceBetween: 120,
        slidesPerView: 'auto',
        centeredSlides: true,
        nested: true,
        speed: 5000,
        autoplay: {
          delay: 0,
        },
      });
    },
    freezeSlider() {
      if (this.swiper && !this.isFrozen) {
        this.swiper.autoplay.stop();
        this.swiper.params.autoplay.delay = 0;
        this.swiper.params.speed = 0;
        this.isFrozen = true;
      }
    },
    unfreezeSlider() {
      if (this.swiper && this.isFrozen) {
        this.swiper.params.autoplay.delay = 5000; // Back to default
        this.swiper.params.speed = 5000; // Back to default
        this.swiper.autoplay.start();
        this.isFrozen = false;
      }
    },
  },
};
</script>
👤Yura

Leave a comment