Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/jfet97/vue-use-infinite-scroll

A Vue composition function that makes infinite scroll a breeze.
https://github.com/jfet97/vue-use-infinite-scroll

Last synced: about 2 months ago
JSON representation

A Vue composition function that makes infinite scroll a breeze.

Awesome Lists containing this project

README

        

# vue-use-infinite-scroll

## Installation

```sh
npm i -S vue-use-infinite-scroll
```

## Usage

### template

```html


{{ errorMessageRef }}

  • {{ item }}




```

### script

```js
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

// 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](https://codesandbox.io/s/vue-use-infinite-scroll-vclfp?file=/src/App.vue) πŸ™‚!