Nuxt.js 프로젝트 필수 플러그인 설정 가이드: Axios, Toast, Swiper 활용법

Nuxt.js 기반의 웹 애플리케이션을 개발할 때 데이터 페칭, 사용자 피드백, 그리고 동적인 UI 구현을 위해 Axios, Toast, Swiper 플러그인은 매우 빈번하게 사용됩니다. 각 플러그인의 효율적인 등록 방법과 실무에서 발생할 수 있는 의존성 이슈를 해결하는 방안을 살펴봅니다.

Axios 인터셉터 및 전역 설정

HTTP 통신을 담당하는 Axios는 Nuxt.js 환경에서 요청 및 응답 인터셉터를 통해 전역적인 헤더 주입이나 에러 핸들링을 수행할 수 있습니다. 아래 코드는 기본 구조를 재구성하여 커스텀 헤더를 추가하고, 401 인증 오류 발생 시 자동으로 리디렉션하도록 로직을 개선한 예시입니다.

export default function ({ $axios, redirect }) {
  $axios.onRequest(requestConfig => {
    // 전역 커스텀 헤더 주입
    requestConfig.headers.common['X-Client-Type'] = 'Nuxt-SSR';
    return requestConfig;
  });

  $axios.onResponse(serverResponse => {
    if (serverResponse.status >= 200 && serverResponse.status < 300) {
      return serverResponse.data;
    }
    return serverResponse;
  });

  $axios.onError(error => {
    const statusCode = error.response ? error.response.status : 500;
    if (statusCode === 401) {
      redirect('/login');
    }
    return Promise.reject(error);
  });
}

BootstrapVue Toast 플러그인 등록

사용자 액션에 대한 시각적 피드백을 제공하기 위해 Toast 메시지를 전역 컴포넌트로 등록합니다. BootstrapVue를 UI 프레임워크로 채택한 경우, 별도의 복잡한 설정 없이 플러그인 모듈만 불러와 즉시 활용할 수 있습니다.

import Vue from 'vue';
import { ToastPlugin } from 'bootstrap-vue';

Vue.use(ToastPlugin);

Swiper 의존성 버전 제어 및 초기화

슬라이더 UI를 구현하기 위해 vue-awesome-swiper를 도입할 때 가장 흔히 겪는 문제는 라이브러리 간의 버전 충돌입니다. 최신 버전을 무조건 설치할 경우 렌더링 오류나 스타일 깨짐 현상이 발생할 수 있으므로, 호환성이 검증된 특정 버전을 명시적으로 설치해야 합니다.

권장 설치 명령어: npm install swiper@5.2.0 vue-awesome-swiper@4.1.1

import Vue from 'vue';
import VueAwesomeSwiper from 'vue-awesome-swiper';
import 'swiper/css/swiper.min.css';

Vue.use(VueAwesomeSwiper);

풀스크린 미디어 캐러셀 컴포넌트 구현

이미지와 비디오를 혼합하여 슬라이드로 구성하고, 슬라이드가 전환될 때 비디오의 재생 및 일시 정지 상태를 자동으로 제어하는 재사용 가능한 풀스크린 캐러셀 컴포넌트입니다. 커스텀 페이지네이션 스타일과 반응형 텍스트 오버레이가 포함되어 있으며, DOM 구조와 변수명을 직관적으로 리팩토링했습니다.

<template>
  <div class="carousel-wrapper">
    <swiper ref="mySwiper" :options="sliderSettings" class="full-screen-slider">
      <swiper-slide v-for="(slide, idx) in mediaItems" :key="idx" class="slide-item">
        <a :href="slide.link || '#'" class="slide-link">
          <img v-if="slide.mediaType === 'image'" :src="slide.url" class="slide-media" alt="slide image" />
          <video v-else :src="slide.url" class="slide-media" loop muted autoplay playsinline></video>
          
          <div class="overlay-bg" v-if="slide.heading || slide.description"></div>
          <div class="text-container" v-if="slide.heading || slide.description">
            <h2 class="main-heading" v-html="slide.heading"></h2>
            <p class="sub-heading" v-html="slide.description"></p>
          </div>
        </a>
      </swiper-slide>
      <div class="custom-pagination" slot="pagination"></div>
    </swiper>
  </div>
</template>

<script>
export default {
  name: 'FullScreenCarousel',
  props: {
    sliderSettings: {
      type: Object,
      default: () => ({
        slidesPerView: 1,
        watchSlidesVisibility: true,
        observer: true,
        observeParents: true,
        on: {
          slideChangeTransitionStart: function () {
            const activeEl = this.slides[this.activeIndex].querySelector('.slide-media');
            const prevEl = this.slides[this.previousIndex].querySelector('.slide-media');
            
            if (prevEl && prevEl.tagName === 'VIDEO') {
              prevEl.pause();
            }
            if (activeEl && activeEl.tagName === 'VIDEO') {
              activeEl.play();
            }
          }
        },
        pagination: {
          el: '.custom-pagination',
          clickable: true
        }
      })
    },
    mediaItems: {
      type: Array,
      default: () => []
    }
  }
};
</script>

<style lang="scss" scoped>
.carousel-wrapper {
  width: 100%;
  position: relative;
}

.full-screen-slider {
  width: 100%;
  height: 100vh;
}

.slide-link {
  display: block;
  width: 100%;
  height: 100%;
  text-decoration: none;
}

.slide-media {
  width: 100%;
  height: 100vh;
  object-fit: cover;
  display: block;
}

.overlay-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(7, 10, 17, 0.4);
  z-index: 2;
}

.text-container {
  position: absolute;
  bottom: 15%;
  left: 10%;
  right: 10%;
  z-index: 10;
  text-align: center;
  color: #fff;

  .main-heading {
    font-size: 4rem;
    font-weight: 800;
    line-height: 1.2;
    margin-bottom: 1rem;
    white-space: pre-wrap;
  }

  .sub-heading {
    font-size: 1.5rem;
    font-weight: 400;
    line-height: 1.5;
    color: #eee;
    white-space: pre-wrap;
  }
}

.custom-pagination {
  position: absolute;
  bottom: 40px;
  width: 100%;
  text-align: center;
  z-index: 20;

  ::v-deep .swiper-pagination-bullet {
    width: 12px;
    height: 12px;
    background: #fff;
    opacity: 0.5;
    border-radius: 50%;
    margin: 0 8px;
    transition: all 0.3s ease;
  }

  ::v-deep .swiper-pagination-bullet-active {
    width: 40px;
    height: 10px;
    background: #ff5a00;
    border-radius: 5px;
    opacity: 1;
  }
}
</style>

태그: Nuxt.js axios BootstrapVue Swiper Vue.js

10월 12일 20:08에 게시됨