Home > database >  Can't use ref to select swiper methods
Can't use ref to select swiper methods

Time:06-28

I am trying to invoke .slideNext() & .slidePrev that come with swiper when the user presses the arrow keys.

I've managed to do this width querySelector like this:

const changeSlide = (event: KeyboardEvent) => {

    const slides = document.querySelector('.swiper').swiper

    if(event.key === 'ArrowLeft') {
      slides.slidePrev();
    } else if (event.key === 'ArrowRight') {
      slides.slideNext();
    }

}

However this method creates warnings and the usage of querySelector is not allowed in general for this project. So instead i wan't to use a ref to select the swiper but i've not yet succeeded at this.

This is what i tried:

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { Navigation } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
import 'swiper/css/navigation';
// just some imports that are needed

const swiperRef = ref();
// swiper as ref

const changeSlide = (event: KeyboardEvent) => {

    const slides = swiperRef.value.swiper
    // instead of querySelector i use the ref.value

    if(event.key === 'ArrowLeft') {
      slides.slidePrev();
    } else if (event.key === 'ArrowRight') {
      slides.slideNext();
    }

}
</script>

<template>
<swiper
  ref="swiperRef"
  :initial-slide="props.initialSlide"
  :slides-per-view="1"
  :space-between="0"
  :modules="[Navigation]"
  navigation
>
  <swiper-slide>  // left out the attributes since they are a mere distraction
    <img/> // left out the attributes since they are a mere distraction
  </swiper-slide>
</swiper>
</template>

The error i get from this code is: enter image description here

CodePudding user response:

You don't have to use this method instead you can just import Keyboard like this:

import { Navigation } from 'swiper';

Add Keyboard to modules and attributes of <swiper> like this:

<swiper :modules="[Navigation, Keyboard]" keyboard />

And add the attribute to <swiper-slide> as well:

<swiper-slide keyboard />

CodePudding user response:

From what I'm seeing in the source code, you can't access the swiper instance using ref on the swiper vue component because it's not exposed.

You have others way to do thought:

  • inside a child component of the <swiper> component, use the useSwiper() component.
  • on the parent component that instanciate the <swiper> component, use the @swiper event. It sends the swiper object once mounted:
<template>
 <swiper @swiper="getRef" />
</template>

<script setup>
const swiper = ref(null)
function getRef (swiperInstance) {
  swiper.value = swiperInstance
}

function next () {
  swiper.value.slideNext() // should work
}
</script>
  • Related