[Vuejs]-Swiper/vue useSwiper() doesn't work, empty value undefined

0👍

useSwiper hook must be used in components which are inside of the Swiper. In your case swiper is undefined.

You can get swiper from onSwiper event codesandbox:

<template>
  <Swiper
    @swiper="onSwiper"
    :navigation="true"
    :modules="modules"
    class="mySwiper"
  >
    <div>
      <button @click.stop="slider.slidePrev()">prev</button>
      <button @click.stop="slider.slideNext()">next</button>
    </div>

    <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-slide>Slide 5</swiper-slide>
    <swiper-slide>Slide 6</swiper-slide><swiper-slide>Slide 7</swiper-slide>
    <swiper-slide>Slide 8</swiper-slide><swiper-slide>Slide 9</swiper-slide>
  </Swiper>
</template>
<script setup>
import { ref } from "vue";
import "swiper/swiper-bundle.min.css";
import { Navigation } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";

const modules = [Navigation];
const slider = ref(null);
const onSwiper = (swiper) => {
  slider.value = swiper;
};
</script>

Leave a comment