Categories
JavaScript Vue

Create a Scrollable Box with vue-perfect-scrollbar

Spread the love

We can create a scrollable box with the vue-perfect-scrollbar package.

First, we install the package by running:

npm install vue-perfect-scrollbar

Then we can register the component that comes with the package in a component and use it by writing:

<template>
  <div id="app">
    <VuePerfectScrollbar
      class="scroll-area"
      v-once
      :settings="settings"
      @ps-scroll-y="scrollHandle"
    >
      <img src="https://placekitten.com/g/300/300" height="300" width="300" alt>
    </VuePerfectScrollbar>
  </div>
</template>

<script>
import VuePerfectScrollbar from "vue-perfect-scrollbar";

export default {
  name: "App",
  components: {
    VuePerfectScrollbar
  },
  data() {
    return {
      settings: {
        maxScrollbarLength: 60
      }
    };
  },
  methods: {
    scrollHandle(evt) {
      console.log(evt);
    }
  }
};
</script>

<style>
.scroll-area {
  position: relative;
  margin: auto;
  width: 200px;
  height: 200px;
}
</style> 

We used the VuePerfectScrollbar component to create a box that have their own scroll bar.

Inside the component, we have an image that we put inside the box.

In the script tags, we add the VuePerfectScrollbar package and registered it in the component property.

In the data method, we return an object with the settings object with the maxScrollbarLength property to set the scrollable length in pixels.

We also have a scroll handler that takes an event object to get us some event data.

In the style tags, we style the scroll area by setting the width and height of the scroll area.

The @ps-scroll-y handler is set to the scrollHandle method so that we can track the scrolling position and other information.

Then we set the class in the VuePerfectScrollbar component.

Now we get a cat picture with horizontal and vertical scrollbars that we can scroll with the mouse wheel or drag with the mouse button.

The scrollbar only shows when we hover over the picture.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.