- Notifications
You must be signed in to change notification settings - Fork32
A Vue component to add intersection-observer to a Vue component or HTML element.
License
heavyy/vue-intersect
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A Vue component to add intersection-observer to a Vue component or HTML element.
TheIntersectionObserver is an amazing API which allows you to observe one or more HTMLElement for when it has entered or left the viewport.
This API has many use cases like, infinite-scroll, lazy-loading or animations when an element enters the viewport.
We've made a basic demo of how you might want to usevue-intersect. The code is available in thegh-pages branch and the part wherevue-intersect is usedcan be found here.
Hackernews infinite scroll demo
Please keep in mind that the demo is not production code. Use it as an inspiration.
Simply install using your favorite package manager 🔥
⚠️ If you're using Vue 3 then installvue-intersect@next
npm install vue-intersect --save
yarn add vue-intersect
The package acts as an abstract component, much like what you may know fromkeep-alive ortransition.
This means that it's basically a "decorator". A component which does not output any markup to the DOM, but adds the functionality under the hood 😱.
<template><intersect@enter="msg = 'Intersected'"@leave="msg = 'Not intersected'"><div>{{ msg }}</div></intersect></template><script>importIntersectfrom'vue-intersect'exportdefault{components:{ Intersect},data(){return{msg:'I will change'}}}</script>
Property | Type | Default | Required | Description |
---|---|---|---|---|
threshold | Array | [0, 0.2] | no | MDN docs |
root | HTMLElement | null | no | MDN docs |
rootMargin | String | 0px 0px 0px 0px | no | MDN docs |
Name | Arguments | Description |
---|---|---|
change | IntersectionObserverEntry | Event fired on any inte. |
enter | IntersectionObserverEntry | Event fired when the element is intersected (visible on the screen) |
leave | IntersectionObserverEntry | Event fired when the element isnot intersected (not visible on the screen) |
destroyed | None | Fired when the underlying element is destroyed |
Theenter andleave event is sugar, for an often performed operation. You still have to set the threshold to e.g. [0, 0.2] (default). If you leave out "0", it will never call theleave event.
The events is compliant with Vue'sevent modifiers. This means that you could add.once
to the events to make sure you only trigger your event handler once.
The IntersectionObserver API is not currently available in all browsers (IE11, Safari and iOS Safari). If you intend to support these browsers, you'll need to add a poylfill to your bundle.
WICG IntersectionObserver Polyfill is highly recommended.
About
A Vue component to add intersection-observer to a Vue component or HTML element.