Categories
Vue 3

Add a Swiper Carousel into a Vue 3 App with Swiper 6

Spread the love

Swiper for Vue.js lets us add a carousel to our Vue 3 app.

In this article, we’ll look at how to add a carousel into our Vue 3 app with Swiper.

Thumbnail Swiper

We can add a thumbnail swiper into our Vue 3 app with Swiper 6.

For instance, we can write:

<template>
  <swiper :thumbs="{ swiper: thumbsSwiper }">
    <swiper-slide v-for="n of 50" :key="n"
      >Slide {{ n }}</swiper-slide
    >
  </swiper>

  <swiper
    @swiper="setThumbsSwiper"
    watch-slides-visibility
    watch-slides-progress
  >
    <swiper-slide v-for="n of 50" :virtualIndex="n" :key="n"
      >Thumbnail {{ n }}</swiper-slide
    >
  </swiper>
</template>

<script>
import SwiperCore, { Thumbs } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";

SwiperCore.use([Thumbs]);

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  data() {
    return {
      thumbsSwiper: null,
    };
  },
  methods: {
    setThumbsSwiper(swiper) {
      this.thumbsSwiper = swiper;
    },
  },
};
</script>

to make the 2nd swiper the thumbnail swiper.

We add the watch-slides-visibility and watch-slides-progress prop to watch the progress of the first slider.

The first swiper is watched because the setThumbsSwiper method is called.

And we set the this.thumbSwiper reactive property to the 2nd swiper.

Effects

Swiper 6 comes with the following effects:

  • Fade
  • Cube
  • Overflow
  • Flip

We can write:

<template>
  <swiper effect="fade">
    <swiper-slide v-for="i of images" :key="i">
      <img :src="i" />
    </swiper-slide>
  </swiper>
</template>

<script>
import SwiperCore, { EffectFade } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper.scss";
import "swiper/components/effect-fade/effect-fade.scss";

SwiperCore.use([EffectFade]);

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  data() {
    return {
      images: [
        "https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo",
        "https://i.picsum.photos/id/25/200/300.jpg?hmac=ScdLbPfGd_kI3MUHvJUb12Fsg1meDQEaHY_mM613BVM",
        "https://i.picsum.photos/id/26/200/300.jpg?hmac=E9i_aIqa_ifLvxqI2b1QTLCnhGQYJ83IpvaDfFM54bU",
      ],
    };
  },
};
</script>

to add the effect prop to the swiper component.

We also have to add the SCSS files for the effect animation and SwiperCore.use([EffectFade]) to add the fade effect.

We can add the other effects in similar ways, except we replace the SCSS and the module we call use with.

Conclusion

We can add thumbnail swipers and swiper effects into our Vue 3 app with Swiper 6.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *