LoginSignup
5
3

Nuxt 3でSwiperを使用する

Last updated at Posted at 2023-06-17

経緯

Nuxt.jsでスライダーを使用する方法を検索すると、vue-awesome-swiperの使用手順が多く紹介されています。しかし、vue-awesome-swiperのプロジェクトを参照すると、使用が非推奨(deprecated)となっており、TypeScriptフレンドリーな公式のSwiper Vue.js Componentsへの移行が推奨されていました。
ただし、公式ページにはSwiper Vue.js Componentsも将来的には削除される可能性との記載があり、最終的にはSwiper Elementの使用を推奨と促されます。
本記事では、このSwiper ElementをNuxt3で使用する手順を簡単にまとめています。

手順

npmからインストール

npm install swiper

使用するコンポーネントでregisterをインポートして実行

<script setup>
import { register } from 'swiper/element/bundle';
register();

</script>

<template>
    <swiper-container>
      <swiper-slide>Slide 1</swiper-slide>
      <swiper-slide>Slide 2</swiper-slide>
      <swiper-slide>Slide 3</swiper-slide>
    </swiper-container>
</template>

この時点でスライダーが動作していますが、コンソールに下記の警告が出ていました。

[Vue warn]: Failed to resolve component: swiper-slide
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.
[Vue warn]: Failed to resolve component: swiper-container
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. 

これを解消するため、nuxt.config.tsに下記を設定します。

export default defineNuxtConfig({
  ...,
  vue: {
    compilerOptions: {
      isCustomElement: (tag) => /^(swiper|swiper-slide|swiper-container)$/.test(tag),
    },
  },
})

まとめ

nuxt3の環境でも簡単にスライダーを導入する事が出来ました。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3