기타

Swiper.js 사용법 및 여러개 사용시 버그 해결

인어공쭈 2024. 7. 11. 11:32

https://swiperjs.com/

 

Swiper - The Most Modern Mobile Touch Slider

Swiper is the most modern free mobile touch slider with hardware accelerated transitions and amazing native behavior.

swiperjs.com

위에서 많은 참고 바람

 

이번에 내가 프로젝트에서 사용한 방법은 가장 나에게 익숙한 CDN link 삽입 방법으로 진행했다.

install 하는건 버전 때문에 웬만하면 거부감이 드는 맘..

위에 사이트에 친절하게 다 나와있긴한데 DOCS 에 대한 부담이 있을수 있으니 간단히 사용법 부터 설명해보겠다.

 

사용법

1) Use Swiper from CDN (주로 index.html 에 복붙)

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css"/>

<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>

 

 

2) 원하는곳에 해당 html 삽입

<!-- Slider main container -->
<div class="swiper">
  <!-- Additional required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
  </div>
  <!-- If we need pagination -->
  <div class="swiper-pagination"></div>

  <!-- If we need navigation buttons -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>

  <!-- If we need scrollbar -->
  <div class="swiper-scrollbar"></div>
</div>

 

 

3) ts/js 파일에 Swiper 작성

const swiper = new Swiper('.swiper', {
  // Optional parameters
  direction: 'vertical',
  loop: true,

  // If we need pagination
  pagination: {
    el: '.swiper-pagination',
  },

  // Navigation arrows
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },

  // And if we need scrollbar
  scrollbar: {
    el: '.swiper-scrollbar',
  },
});

 

4) 사용법 끝

 

 

여기까지가 기본적인 사용법이다. 여기서 안되는건 거의 없긴하다. 매우 쉬움, 하지만 스와이퍼를 공통으로 사용할경우 버그가 발생하는 경우가 있었다. 나같은 경우엔 공통 이미지 컴포넌트를 만들어서 여러군데서 사용을 했는데 그러다 보니깐 메인에서 됐는데 서브에서 안되는경우가 생겼다. 

 

살펴보니깐 기존 코드가 위에 처럼 컨트롤러가 하나기 때문에 제대로 동작을 안하는것이었다. 그래서 이후 코드를 수정해서 항상 아이디값을 다르게 만들어서 버그를 해결했다.

 

버그 해결방법

아래는 랜덤 숫자로 아이디값을 수정한 스와이퍼 설정 코드다.

swiperId = 'swiper-' + Math.random().toString(36).substring(2, 15);

  ngAfterViewInit() {
    this.swiper = new Swiper(`#${this.swiperId}`, {
      // Swiper 설정
      navigation: {
        nextEl: '.btn-photo-prev',
        prevEl: '.btn-photo-next',
      },
      on: {
        slideChange: () => {
          this.currentIndex = this.swiper.realIndex;
          this.swipeEvent.emit(this.currentIndex);
          this.cd.detectChanges();
        },
      },
    });
    this.swiper.slideTo(this.currentSlide, 0);
  }

 

* 추가로 스와이퍼 변화감지를 통해서 다양한 값을 추출해낼수 있는데 그건 slideChange 라는 옵션을 써서 this.swiper + (추출 원하는값) 를 하면 된다. 나는 활성화된 인덱스 값을 화면에 노출해야되기 때문에 realIndex 값을 가지고 왔다.

반응형

'기타' 카테고리의 다른 글

HTTPS & HTTP 네트워크  (0) 2024.09.17
브라우저 랜더링 과정 - CRP(Critical Rendering Path)  (0) 2024.09.17
vscode Prettier 설정  (0) 2024.04.18
구글 계정 로그인 구현 (OAuth)  (0) 2023.06.22
웹팩(WebPack)이란?  (0) 2023.05.22