Reputation: 151
I want to use slideNext() method in Swiper JS. However, from the documentation of Swiper JS for Svelte, there is no example on showing how to access to method in Svelte. In React, there is a hook called useSwiper but no such thing in Svelte. Does anyone know how?
Upvotes: 4
Views: 2840
Reputation: 194
Since Swiper JS no longer supports Svelte directly (and soon will probably drop support for all other frameworks), we should now use Swiper as a custom HTML element (web component) Swiper component. Below is an example of how to use Swiper in Svelte:
// App.svelte
<script lang="ts">
import { register } from 'swiper/element/bundle';
register(); // register swiper components
// ...
</script>
// SomeComponent.svelte
<script lang="ts">
import {type SwiperContainer} from 'swiper/element/bundle';
import {onMount} from "svelte";
let swiperEl: SwiperContainer|undefined;
let swiperNextElem: HTMLElement|undefined;
let swiperPrevElem: HTMLElement|undefined;
onMount(() => {
if(swiperEl != undefined && swiperNextElem != undefined && swiperPrevElem != undefined) {
const swiperParams = {
navigation: {
nextEl: swiperNextElem,
prevEl: swiperPrevElem,
},
slidesPerView: 1,
loop: true,
}
// now we need to assign all parameters to Swiper element
Object.assign(swiperEl, swiperParams);
// and now initialize it
swiperEl.initialize();
}
});
</script>
<div>
<swiper-container init="false" bind:this={swiperEl}>
<swiper-slide><div>CUSTOM ELEMENT</div></swiper-slide>
<swiper-slide><div>CUSTOM ELEMENT</div></swiper-slide>
<swiper-slide><div>CUSTOM ELEMENT</div></swiper-slide>
</swiper-container>
<div bind:this={swiperPrevElem}>Prev</div>
<div bind:this={swiperNextElem}>Next</div>
</div>
Upvotes: 1
Reputation: 185553
The API is a bit weird. It should be using a bindable prop but you need to handle the swiper
event instead to get the API instance.
<script>
// ...
let swiper;
</script>
<Swiper on:swiper={e => swiper = e.detail[0]}>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
</Swiper>
<button type=button on:click={() => swiper.slidePrev()}>Previous</button>
<button type=button on:click={() => swiper.slideNext()}>Next</button>
Upvotes: 6