Skip to content

jfet97/vue-use-infinite-scroll

Repository files navigation

vue-use-infinite-scroll

Installation

npm i -S vue-use-infinite-scroll

Usage

template

<div>
    <span>{{ errorMessageRef }}</span>
    <ul>
        <li v-for="item in itemsRef" :key="item.id">{{ item }}</li>

        <!-- DOM element used as trigger -->
        <div ref="intersectionTrigger"></div>
    </ul>
</div>

script

import { ref, watch } from 'vue'
import { makeUseInfiniteScroll } from 'vue-use-infinite-scroll'

export default {
    setup() {
        // INTERSECTION OBSERVER

        // set the intersection options object
        // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
        const useInfiniteScroll = makeUseInfiniteScroll({}) // the argument is optional

        // create the template ref for the element that
        // will trigger the intersection observer
        const intersectionTrigger = ref(null) // as Ref<HTMLElement>

        // useInfiniteScroll returns a pageRef, starting from page 1,
        // which changes we should listen to fetch more data
        const pageRef = useInfiniteScroll(intersectionTrigger)

        watch(
            pageRef,
            (page) => {
                fetchItems(page)
            },
            { immediate: true }
        )

        // DATA

        const itemsRef = ref([])
        const errorMessageRef = ref('')

        async function fetchItems(page) {
            fetch(`https://jsonplaceholder.typicode.com/comments?_page=${page}&_limit=10`)
                .then((res) => res.json())
                .then((data) => itemsRef.value.push(...data))
                .catch((error) => (errorMessageRef.value = error.message))
        }

        return { intersectionTrigger, itemsRef, errorMessageRef }
    },
}

Try it here 🙂!

About

A Vue composition function that makes infinite scroll a breeze.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy