How to Build a Modern Image Slider with Swiper
Tags: vue, javascript, tutorial, css
Published: 2022-03-28 14:54:09

Slideshows are fantastic for displaying crucial information or images to the users viewing a website. Amongst other uses, you can create an image slider to draw users' attention to specific products on your e-commerce site.

Though building an image slider is very much possible with HTML, CSS and JavaScript, using a library is definitely a more convenient approach. You get to save precious time that could have been spent on writing code, while also getting a ton of other customization features that may have been difficult to implement by yourself.

In this tutorial, we'll learn how to include a modern image slider in a Vue application. We'll build our image slider using [Swiper](https://swiperjs.com/). Swiper is a modern, library-agnostic solution for creating touch sliders in web and mobile applications.

Here's the preview of our image slider:

![Swiper Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zcfb4fhmt2sgynz8yw2s.gif)

Before we start, please note that you need to have a recent version of Node js and npm installed on your computer. Don't have Nodejs or npm installed? Download the [installer from Node.js](https://nodejs.org/en/download/).

## Create Your Vue Application
Let's start by installing the Vue CLI globally (if you haven't already done so):

```js
npm install -g @vue/cli
```
Next, create a new Vue application:

```js
vue create my-sliders
```
After a while, Vue should generate your new application. When this is done, run the following commands to start your new vue application:

```js
cd my-sliders
vue serve
```

Finally, you should move the images you want to use in your sliders into the **src/assets** folder in your project.

With the basic setup complete, it's time to install swiper js using the node package manager (npm).

## Getting Started with Swiper JS in your Vue Project
### 1- Installation
To install swiper js, run the following command:

```js
npm i swiper
```
This will install the swiper package from npm and include it as a dependency under package.json.

### 2 - Building our Image Slider
Let's start building our image slider.

Open your **App.vue** file and replace the content of your `<script>` tag with this (delete the **components ** folder in your src directory, we don't need it):

```js
<script>
 // import Swiper core and required modules
  import SwiperCore, { Navigation, Parallax } from 'swiper';  

  // Import Swiper Vue.js components
  import { Swiper, SwiperSlide } from 'swiper/vue';  

  // Import Swiper styles
  import 'swiper/css';
  import 'swiper/css/navigation';

  // Import images to be used as slide
 import image1 from "./assets/first-slide.jpg";
  import image2 from "./assets/second-slide.jpg";
  import image3 from "./assets/final-slide.jpg";

  SwiperCore.use([Navigation, Parallax, Scrollbar, A11y]);

  export default {
    components: {
      Swiper,
      SwiperSlide,
    },
    data() {
      return {
        parallaxSwiperWidth: 0,
        images: [{
          id: 1,
          imageUrl: image1
        },
        {
          id: 2,
          imageUrl: image2
        },
        {
          id: 3,
          imageUrl: image3
        }]
      }
    }    
  };
</script>
```

We import the swiper core module, along with the navigation, parallax and blah modules. We also import two Vue components from the package, these are Swiper (the slides container) and **SwiperSlide** (for creating a slide).

Then we import the styles for each module, and the images we want to use in each of the slides. These images are returned from the **data()** function so we can access it in our template.

The modules are then registered on the **SwiperCore** module.

To create slides on the view, replace the content of your `<template>` element with the following:

```js
<template>
  <swiper
    class="parallax-slider"
    parallax
    grabCursor
    navigation
  >
    <swiper-slide v-for="image in images" :key="image.id">
      <img :src="image.imageUrl">  
    </swiper-slide>    
    ...
  </swiper>
</template>
```
The **grabCursor** property will enable us to progress through the slides by grabbing and pulling on each slide. The **navigation** property provides two icons on our slide that, upon clicking, will move to either the next or previous slide in the collection.

Save the file, run `vue serve` and go to **localhost:8000** to see the results:

![Image Slider](https://cdn.hashnode.com/res/hashnode/image/upload/v1648137766504/4LnYsU_3Q.png)

Here you can see that the default navigation functionality from swiper is used. We can create our own custom navigation, and I'll show you how to do just that in the next section.

### 3 - Adding Custom Navigation
You might want to use your own custom navigation in lieu of the default provided by Swiper js. For our custom navigation, we'll use a couple of navigation icons from Font Awesome.

Start by copying the following CDN link to Font Awesome, and pasting the link inside your **public/index.html** file:

```css
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
```

Next, we'll add our new navigation icons inside our `<swiper>` and just above our `<swiper-slide>` tags.

```html
<div class="parallax-slider-navigation" style="display: flex; justify-content: space-between; padding: 1rem;">
      <div class="nav-indicator prevArrow fa-2x">
        <i class="fa-solid fa-backward"></i> Prev
      </div>
      <div class="nav-indicator nextArrow fa-2x">
        Next <i class="fa-solid fa-forward"></i>
      </div>
</div>    
```
Two container `<div>` elements are created and assigned the class names `nav-indicator`, `prevArrow/nextArrow` and `fa-2x`. The first two, which are both specific to swiper js, will give swiper information about our nav. `fa-2x` is specific to Font Awesome, and it increases the size of our icons two folds.

Speaking of icons, if you elect to install and use Font Awesome as a Vue component, you must first register font-awesome as a component in your **App.vue** file

```js
export default {
    components: {
      Swiper,
      SwiperSlide,
      FontAwesomeIcon
    },
    data() {
      // return images
    }    
  };
```

before using it in the template in place of the `<i>` tags:

```html
<font-awesome-icon icon="fa-solid fa-backward" />
<font-awesome-icon icon="fa-solid fa-forward" />
```

Now we must tell swiper js about the elements responsible for navigating the slider by referencing both `.prevArrow` and `.nextArrow` elements in the navigation property of the slider:

```html
<swiper
    class="parallax-slider"
    parallax
    grabCursor
    :navigation="{ nextEl: '.nextArrow', prevEl: '.prevArrow'}"
  >  
        ...
  </swiper>
``` 

Save your file and go to your browser to see the output. 

![Custom Sliders](https://cdn.hashnode.com/res/hashnode/image/upload/v1648301757462/ZFgJTHwwN.png)

The default navigation from swiper js has now been replaced by our custom navigation.

## Swiper JS vs Slick
[Slick](https://kenwheeler.github.io/slick/) is another great option for creating slides and carousels in your web app. Slides created with slick are fully responsive and scales with its container. 

You are also presented with the option to enable or display the sliding feature. Not to mention that slick also provides desktop mouse dragging functionality, just like Swiperjs.

### 1 - Creating single items
Creating a single slider is as easy as this:

```js
$('.single-item').slick();
```

![Single Slide with Slick](https://cdn.hashnode.com/res/hashnode/image/upload/v1648303314227/ruwVDlIl7.png)

### 2 - Creating Multiple Items
For a carousel with multiple items, you need to pass in more properties:

```js
$('.multiple-items').slick({
  infinite: true,
  slidesToShow: 3,
  slidesToScroll: 3
});
```

![Multiple Slides Carousel with Slick](https://cdn.hashnode.com/res/hashnode/image/upload/v1648303572861/kjkNzHHYf.png)

Make sure to set the class **.multiple-items** on every slide's HTML tag.

## Wrapping Up
To recap, we created a fresh Vue project and installed the swiper js package from npm. We then built a simple image slider using the default navigation from swiper, before implementing our own custom navigations.

We also compared Swiper to Slick, another solution for creating sliders and carousels. We saw the code for creating a carousel containing a single item and a carousel containing multiple items at a time.

Have a great week.