Splidejs / svelte-splide

Svelte component for the Splide slider/carousel.
https://splidejs.com/
MIT License
82 stars 9 forks source link

Property perPage in options doesn't bind to changes that happen dynamically #6

Closed andishehk closed 2 years ago

andishehk commented 2 years ago

Checks

Version

0.2.1

Description

I am trying to change perPage value in options based on window width. If my screen is greater than 900px I want to show 2 items but for smaller screens, just 1 item per page.

This is my code:

<script>
  import { Splide, SplideSlide } from '@splidejs/svelte-splide';
  import '@splidejs/svelte-splide/css';
  let items = [
    { title: 'title1' },
    { title: 'title2' },
    { title: 'title3' },
    { title: 'title4' },
    { title: 'title5' },
    { title: 'title6' },
  ];

  let innerWidth;
  $: tileNumber = innerWidth > 900 ? 2 : 1;
  $: carouselOptions = {
    gap: '1rem',
    padding: '2rem',
    focus: 0,
    perPage: tileNumber,
    perMove: 1,
    arrows: false,
    pagination: false,
  };
</script>

<svelte:window bind:innerWidth />
<div class="container">
<div class="tileNumber">tileNumber: {tileNumber}</div>

<Splide aria-label="item title" bind:options="{carouselOptions}">
  {#each items as item}
  <SplideSlide>
    <div class="tile">{item.title}</div>
  </SplideSlide>
  {/each}
</Splide>
</div>

<style>
.tile {
  width: 100%; 
  height: 10rem; 
  background-color: gray;
}
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

}
.tileNumber{
  width: 100%; 
  height: 2rem;
  text-align: center;
  font-size: 30px;
  padding: 20px;
}
</style>

Reproduction Link

https://codesandbox.io/s/test-splide-dynamic-options-npbsy9?file=/App.svelte

Steps to Reproduce

  1. Make the initial screen smaller than 900px and you would see one item per page as expected
  2. Make the screen bigger, and you can see 2 items per page as expected
  3. Now drag the screen to smaller size again, and you still see 2 items per page instead of 1 (while tileNumber is being shown as 1)

Expected Behaviour

The number of items per page should match tileNumber, which means when the tileNumber shows 1, we should see 1 item per page (for small screens), and when it is 2, we should be able to see 2 items per page.

NaotoshiFujita commented 2 years ago

Use breakpoints option instead: https://splidejs.com/guides/options/#breakpoints

You do not have to observe the window width manually.