Martin Weissenboeck
Martin Weissenboeck

Reputation: 723

SvelteKit and Swiper 6.8.1: how to use slideTo(index)

Slider 6.8.1 works well with SvelteKit. I would like to be able to select a certain slide also by program. This is apparently possible with swiper.slideTo(index, speed).

swiper is created for example like this:

const swiper = new Swiper('.swiper-container', {
  speed: 400,
  spaceBetween: 100,
});

However, SvelteKit requires Swiper to be imported like this:

import Swiper from 'swiper/esm/svelte/swiper.svelte';

But then new Swiper returns the error message

__vite_ssr_import_1__.default is not a constructor

This is quite understandable, but how to solve the problem?

Upvotes: 1

Views: 1217

Answers (1)

johannchopin
johannchopin

Reputation: 14873

If you import Swiper from 'swiper/esm/svelte/swiper.svelte' then it's no more the class but the svelte component that you will use in your template like:

  <Swiper>
    <SwiperSlide>Slide 1</SwiperSlide>
    <SwiperSlide>Slide 2</SwiperSlide>
    ...
  </Swiper>

In your case you need both the component and the class that you will initialise during the component mount:

  import SwiperComponent from "swiper/esm/svelte/swiper.svelte";
  import { Swiper } from "swiper";

You can then store the Swiper instance in a reactive variable like in this example:

<script>
  import { onMount } from "svelte";

  import SwiperComponent from "swiper/esm/svelte/swiper.svelte";
  import SwiperSlide from "swiper/esm/svelte/swiper-slide.svelte";
  import { Swiper } from "swiper";
  import "swiper/swiper.scss";

  let swiper = null;

  onMount(() => {

    // initialise the swiper
    swiper = new Swiper(".swiper-container", {
      loop: true
    });

    // go to slide 6 after one second
    setTimeout(() => {
      swiper.slideTo(6, 1000);
    }, 1000);
  });
</script>

<SwiperComponent>
    <SwiperSlide>Slide 1</SwiperSlide>
    <SwiperSlide>Slide 2</SwiperSlide>
    ...
</SwiperComponent>

Edit damp-tdd-tz70n

Upvotes: 3

Related Questions