vue-use-infinite-scroll

A Vue composition function that makes infinite scroll a breeze
1,860 111
Install
npm install vue-use-infinite-scroll
Latest Version:0.0.3
Vue:2
License:MIT
Last Updated:Jul 18, 2023
Links: GitHub  ·  npm
Maintainer: jfet97

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, watchEffect } 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 🙂!

Related Packages

vue-virtual-collection

Vue component for efficiently rendering large collection data

34,838 637
@jfm/vue-infinite-scroll

A bidirectional infinite scroll component for Vue.js

1,565 2
vue-infinite-iscroll

A vue infinite scroll

1,037 4
vue-composable-function-tester

A test utility for testing vue composable functions

936 1
chronocraft-scroller-vue

A Vue 3 Dynamic and Versatile High Performance Infinite Scroller Component

1,647 3

Version History

Version Released Vue License
0.0.3 ^2.6.11 MIT
0.0.2 ^2.6.11 MIT
0.0.1 ^2.6.11 MIT