LoginSignup
18
16

More than 3 years have passed since last update.

vue-awesome-swiperが動かなくてハマった

Last updated at Posted at 2020-07-22

Nuxt.jsでSwiperを使ってみたが、うまく動かなくてハマったけどなんとか解決。

環境

  • Nuxt.js v2.4.0
  • vue-awesome-swiper v4.1.1
  • swiper v6.0.4

現象

配布サイトや他の記事参考にインストール・設置するも、スワイプやドラッグでのスライド以外できない。
autoplayやfade、pagenationなど動かず。

参考にした記事等
- vue-awesome-swiper
- Nuxt.jsで高機能スライダーSwiperを使ってみた
- Nuxt.js + Swiper スライダーの作り方

結論

Global Registrationの設定をいじったらできるようになった。

以下のページが解決のきっかけになった。
https://github.com/surmon-china/vue-awesome-swiper/issues/688

よくみたら配布サイトにも書いてった。(Custom Build with Swiperの項目)

インストール

配布サイトと同様。
swiperとvue-awesome-swiperの両方必要。

npm install swiper vue-awesome-swiper --save

pluginsの設定

ここの設定を調整した。
pluginsのディレクトリにvue-awesome-swiper.jsを新規作成。

plugins/vue-awesome-swiper.js
import Vue from 'vue'
import Swiper from 'swiper/swiper-bundle.esm'
import getAwesomeSwiper from 'vue-awesome-swiper/dist/exporter'
Vue.use(getAwesomeSwiper(Swiper))
import 'swiper/swiper-bundle.css'

配布サイトではswiper/swiper.esmを読み込んで、使うcomponentを指定していたが、
面倒なのでswiper/swiper-bundle.esmを読み込んで指定なしで全component使えるようにした。

これがベストなのかは正直わからないが、必要な機能だけ読み込たい場合は配布サイトのCustom Build with Swiperの項目を参考にしてみたら良いだろう。

nuxt.config.jsでの読み込み

nuxt.config.js
plugins: [
    { src: '@/plugins/vue-awesome-swiper.js', ssr: false }
],

...

build{
    vendor: [
      'vue-awesome-swiper',
    ],
}

Swiperの設定

pages/index.vue

<div class="swiper-container" v-swiper="swiperOption">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide1</div>
    <div class="swiper-slide">Slide2</div>
    <div class="swiper-slide">Slide3</div>
  </div>
  <div class="swiper-pagination"></div>
</div>

...

export default {
    data () {
        return {
            swiperOption: {
                effect: 'fade',
                loop: true,
                autoplay: {
                  delay: 5000,
                },
                pagination: {
                  el: '.swiper-pagination',
                  clickable: true
                },
            }
        }
    }
}

これで動くはず。
swiperは便利だけど、バージョンごとに若干使い方が変わってくるので毎回ハマってしまい苦手意識がある。。

18
16
3

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
18
16