vLazy directive

Scroll an element into view. Adding a value to the binding permits you to define a y-offset. This is useful if there's a navbar on top of your page.

Usage

Register the following directive/s:

import vLazy from '../../directives/vLazy.js';

// ...

app.directive('lazy', vLazy)

Example

This directive is a required by the QImage component

<template>
  <q-image src="../assets/img/my-image.png" />
</template>

Full directive's code

vLazy.js

export default {
  mounted: (el, binding) => {
    const loadImage = () => {
      if (el) {
        el.addEventListener('load', () => {
          setTimeout(() => el.classList.add(binding.value), 100);
        });
        el.addEventListener('error', () => console.log('error'));
        el.src = el.dataset.url;
      }
    };

    const handleIntersect = (entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          loadImage();
          observer.unobserve(el);
        }
      });
    };

    const createObserver = () => {
      const options = {
        root: null,
        threshold: 0,
      };
      const observer = new IntersectionObserver(handleIntersect, options);
      observer.observe(el);
    }
    if (window['IntersectionObserver']) {
      createObserver();
    } else {
      loadImage();
    }
  },
};