Categories
JavaScript Vue

Using the Intersection Observer API in a Vue App with Vue Intersect

Spread the love

We can use the Vue Intersect package to use the intersection observer API in our app.

To install it, we run:

npm install vue-intersect --save

or:

yarn add vue-intersect

Then we can use it by using the intersect component that comes with the package.

For instance, we can write:

<template>
  <div id="app">
    <div style="height: 300px; overflow-y: scroll">
      <intersect @enter="onEnter" @leave="onLeave" v-for="a of arr" :key="a">
        <div :id="a">{{ a }}</div>
      </intersect>
    </div>
    <div>in screen: {{inScreen.join(', ')}}</div>
  </div>
</template>

<script>
import Intersect from "vue-intersect";

export default {
  name: "App",
  components: { Intersect },
  data() {
    return {
      arr: Array(100)
        .fill()
        .map((_, i) => i),
      inScreen: []
    };
  },
  methods: {
    onEnter(e) {
      this.inScreen.push(e[0].target.id);
      this.inScreen = [...new Set(this.inScreen)];
    },
    onLeave(e) {
      const index = this.inScreen.indexOf(e[0].target.id);
      this.inScreen.splice(index, 1);
      this.inScreen = [...new Set(this.inScreen)];
    }
  }
};
</script>

We have the intersect component, which we pass the enter and leave handlers into.

We set them to onEnter and onLeave respectively.

In the methods, we have the e object, which is the event objects.

We assigned the ID to each item that we rendered with v-for, so we can get the id property of those elements that enter the screen in onEnter and the ones the left the screen in onLeave.

We add the ones that are on the screen to the inScreen array.

Likewise, we do the same with the ones that left the screen in onLeave.

We remove the duplicates by converting them to a set and then converting back to an array.

The div is made scrollable by setting its height to 300px and setting the overflow-y property to scroll.

Then when the elements enter or leave the div’s displayed area, those callbacks will be called.

We displayed the IDs of the items that are displayed in the bottom div.

vue-intersect lets us use the intersection observer API to detect if something is in the viewport easily.

Leave a Reply

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