Article

Wrapping Intersection Observer in a Vue component

Remco Hendriksen on Nov 16, 2020
component javascript events
Last updated: Dec 15, 2020

The benefit of having a intersection component is that you don't have to write the Intersection Observer code over and over again. Just include it as a component and listen to the intersect event.

Code

<template>
  <div class="observer" style="display: block; height: 1px; width: 1px" />
</template>
<script>
export default {
  data() {
    return {
      observer: null,
    }
  },
  mounted() {
    this.observer = new IntersectionObserver(this.onIntersect, {
      root: null,
      rootMargin: '0px 0px 100px 0px',
      threshold: 0,
    })

    this.observer.observe(this.$el)
  },

  destroyed() {
    this.observer.disconnect()
    this.observer = null
  },

  methods: {
    onIntersect(event) {
      const isIntersecting = event.find((entry) => {
        return entry.isIntersecting
      })
      if (isIntersecting) {
        this.$emit('intersect', event)
      }
    },
  },
}
</script>

How to use

This is how you would implement it in a category page for example.

<template>
  <div class="container">
    <div
      v-for="article in articles">
      {{ article.description }}
    </div>
    <intersection-observer @intersect="loadMore" />
  </div>
</template>
<script>
import IntersectionObserver from '~/components/IntersectionObserver'
export default {
  components: {
    IntersectionObserver
  },
  data() {
    articles: []
  },
  methods: {
    async loadMore() {
      const result = await this.$axios.get('https://your-api-call.com')
      result.items.forEach(article => {
        this.articles.push(article)
      })
    }
}
</script>
Leave a comment below if you have got any questions about this article.

Leave a comment

More articles