LoginSignup
13
12

More than 1 year has passed since last update.

【Nuxt.js】vue-awesome-swiperを導入し、カルーセルを表示させてみる

Last updated at Posted at 2020-03-06

Nuxt.jsでvuetify.jsを使用しています。今回はスライダーの実装について検討したSwiperについてご紹介します。

VuetifyにはCarouselsのコンポーネントが含まれているのですが、複数の画像を表示させたりする機能がなく別のライブラリを探していました。
https://vuetifyjs.com/en/components/carousels

まず候補にあがったのはvue-carouselですが、アニメーションの機能など少ないこともありvue-awesome-swiperを導入することにしました。
https://github.com/surmon-china/vue-awesome-swiper?ref=kabanoki.net
https://github.surmon.me/vue-awesome-swiper/?ref=madewithvuejs.com

もともとSwiper自体がjQueryに以前せずに使えたこともあり、Vue.jsを使う前からも使用していました。
Githubでも2万超えのスターを押されている人気のライブラリーです。
それをVue.js用に使用できるよう開発されたのがvue-awesome-swiperです。

vue-awesome-swiperをプロジェクトに追加

まずはvue-awesome-swiperをプロジェクトに追加します。

yarn

yarn add vue-awesome-swiper

pluginsにフォルダに追加

pluginsにフォルダの中にswiper.jsを作成します。
vueをインポートしてVueAwesomeSwiperを使う宣言をします。
swiperのcssもここで読み込む用にします。

plugins/swiper.js
import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'

Vue.use(VueAwesomeSwiper)

nuxt.config.jsに追記する

nuxt.config.jsのpluginsに追記します。
SSR対応済みのプラグインであれば、pluginsの ssr:false 記述は不要ですが、非対応のものでここを設定してなかったらエラーがでます。

nuxt.config.js

  plugins: [
    { src: '~/plugins/swiper.js', ssr: false }
  ],

テンプレートを準備する

swiperが全体を囲い、swiper-slideで各スライドの部分を表示させます。

index.vue
<template>
  <section>
    <swiper>
      <swiper-slide>スライド1</swiper-slide>
      <swiper-slide>スライド2</swiper-slide>
      <swiper-slide>スライド3</swiper-slide>
    </swiper>
  </section>
</template>

Swiperのオプションを使ってみる

swiperに:options="swiperOption"を追加します。
Swiper.jsのときに使用した機能が使えます。下記を参考にたくさんのオプションが使えます。
Vue-Awesome-Swiper

オプションの設定

index.vue
<template>
  <section>
    <swiper :options="swiperOption">
      <swiper-slide>スライド1</swiper-slide>
      <swiper-slide>スライド2</swiper-slide>
      <swiper-slide>スライド3</swiper-slide>
			<div class="swiper-pagination" slot="pagination"></div>
			<div class="swiper-button-prev" slot="button-prev"></div>
			<div class="swiper-button-next" slot="button-next"></div>
    </swiper>
  </section>
</template>

<script>
export default {
	data () {
		return {
			swiperOption: {
				autoplay: {
					delay: 2500,
					disableOnInteraction: false
				},
				pagination: {
          el: '.swiper-pagination',
          clickable: true
        },
				slidesPerView: 2,
				centeredSlides: true,
				spaceBetween: 5,
				loop: true,
				navigation: {
					nextEl: '.swiper-button-next',
					prevEl: '.swiper-button-prev'
				}
			}
		}
	}
}
</script>

ページネーションと前後へのナビを追加した形で一般的なナビはこんなところでしょうか。

13
12
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
13
12