InfiniteScroll
Automatically load the next page when a list reaches the bottom, for long lists that load more as you scroll.
Import
import { HuiInfiniteScroll } from '@nscode/handy-ui'
Basic usage
Place the list in HuiInfiniteScroll, inside a scrolling container with a height and overflow: auto. load returns a Promise that resolves when loading finishes. Resolving to false means there is no more data: the completed message appears and further loading stops. This example loads 10 entries at a time, up to 50:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll } from '@nscode/handy-ui'
interface Notice {
id: number
text: string
}
const names = ['张伟', '王芳', '李娜', '刘洋', '陈静']
const actions = [
'submitted an expense claim',
'commented on your article',
'followed you',
'updated project progress'
]
// A timer simulates an API request
const fetchPage = (start: number) =>
new Promise<Notice[]>((resolve) => {
window.setTimeout(() => {
const page = Array.from({ length: 10 }, (_, i) => {
const n = start + i
return { id: n + 1, text: `${names[n % 5]}${actions[n % 4]}` }
})
resolve(page)
}, 600)
})
const list = ref<Notice[]>([])
const load = async () => {
const page = await fetchPage(list.value.length)
list.value.push(...page)
return list.value.length < 50
}
</script>
<template>
<div class="box">
<HuiInfiniteScroll :load="load">
<div v-for="item in list" :key="item.id" class="item">#{{ item.id }} {{ item.text }}</div>
</HuiInfiniteScroll>
</div>
</template>
<style scoped>
.box {
height: 300px;
overflow-y: auto;
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
</style>
On mount, loading starts automatically if the list end is already visible, such as when the list is initially empty. Loading continues until the container is filled or load returns false.
Loading in advance
distance sets how many pixels before the content bottom loading begins. The default is 0 (at the bottom). With 200, the next page starts loading 200px in advance, reducing the time spent waiting for a loading indicator.
These lists differ only in distance. Scroll each one to compare:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll, HuiSpace } from '@nscode/handy-ui'
const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安']
const makePage = (start: number) =>
Array.from({ length: 10 }, (_, i) => `${cities[(start + i) % 8]} store ${start + i + 1}`)
const listA = ref<string[]>([])
const listB = ref<string[]>([])
const loadA = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 600))
listA.value.push(...makePage(listA.value.length))
return listA.value.length < 100
}
const loadB = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 600))
listB.value.push(...makePage(listB.value.length))
return listB.value.length < 100
}
</script>
<template>
<HuiSpace fill align="start">
<div>
<p class="demo-label">distance = 0 (default): {{ listA.length }} entries loaded</p>
<div class="box">
<HuiInfiniteScroll :load="loadA">
<div v-for="item in listA" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
</div>
</div>
<div>
<p class="demo-label">distance = 200: {{ listB.length }} entries loaded</p>
<div class="box">
<HuiInfiniteScroll :load="loadB" :distance="200">
<div v-for="item in listB" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
</div>
</div>
</HuiSpace>
</template>
<style scoped>
.demo-label {
margin: 0 0 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
.box {
height: 300px;
overflow-y: auto;
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
</style>
Immediate loading
The component already loads automatically when the list end is visible; immediate is not needed for that. Use immediate to request once immediately after mounting even when existing data puts the end outside the viewport, such as displaying 20 cached entries and fetching the next page on mount.
Both lists start with 20 entries. The right list uses immediate and loads another 10 immediately after mounting:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll, HuiSpace } from '@nscode/handy-ui'
const makePage = (start: number) =>
Array.from({ length: 10 }, (_, i) => `Article ${start + i + 1}: Weekly technology report`)
const listA = ref<string[]>([...makePage(0), ...makePage(10)])
const listB = ref<string[]>([...makePage(0), ...makePage(10)])
const loadA = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 600))
listA.value.push(...makePage(listA.value.length))
return listA.value.length < 60
}
const loadB = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 600))
listB.value.push(...makePage(listB.value.length))
return listB.value.length < 60
}
</script>
<template>
<HuiSpace fill align="start">
<div>
<p class="demo-label">Without immediate: {{ listA.length }} entries</p>
<div class="box">
<HuiInfiniteScroll :load="loadA">
<div v-for="item in listA" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
</div>
</div>
<div>
<p class="demo-label">immediate: {{ listB.length }} entries</p>
<div class="box">
<HuiInfiniteScroll :load="loadB" immediate>
<div v-for="item in listB" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
</div>
</div>
</HuiSpace>
</template>
<style scoped>
.demo-label {
margin: 0 0 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
.box {
height: 240px;
overflow-y: auto;
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
</style>
Disabled and external loading states
disabled prevents loading. loading displays the loading state and also prevents new requests, allowing external loading management. After either returns to false, loading starts immediately if the list end is visible.
Enable either switch and scroll to the bottom: no new load starts. Turn it off to resume:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const list = ref<string[]>([])
const load = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 600))
const start = list.value.length
list.value.push(...Array.from({ length: 10 }, (_, i) => `Task ${start + i + 1}`))
return list.value.length < 100
}
const noPermission = ref(false)
const refreshing = ref(false)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch v-model="noPermission" active-text="Disabled" />
<HuiSwitch v-model="refreshing" active-text="External loading" />
</HuiSpace>
<div class="box">
<HuiInfiniteScroll :load="load" :disabled="noPermission" :loading="refreshing">
<div v-for="item in list" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
</div>
</HuiSpace>
</template>
<style scoped>
.box {
height: 300px;
overflow-y: auto;
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
</style>
Loading events
loadStart is emitted when loading begins, and loadComplete when it succeeds. The hasMore argument indicates whether another page exists. This example has 30 entries, so the last hasMore is false:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll, HuiSpace } from '@nscode/handy-ui'
const list = ref<string[]>([])
const events = ref<string[]>([])
const record = (text: string) => {
events.value = [...events.value, text].slice(-6)
}
const load = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 600))
const start = list.value.length
list.value.push(
...Array.from({ length: 10 }, (_, i) => `Product review ${start + i + 1}: Fast delivery`)
)
return list.value.length < 30
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<div class="box">
<HuiInfiniteScroll
:load="load"
@load-start="record('loadStart')"
@load-complete="record(`loadComplete:hasMore = ${$event}`)"
>
<div v-for="item in list" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
</div>
<p>Recent events: {{ events.join(',') || 'None yet' }}</p>
</HuiSpace>
</template>
<style scoped>
.box {
height: 240px;
overflow-y: auto;
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
</style>
Custom loading content
The loading slot replaces the loading message, and complete replaces the completed message. This example has 30 entries; scroll to see both slots:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiIcon, HuiInfiniteScroll } from '@nscode/handy-ui'
const list = ref<string[]>([])
const load = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 1000))
const start = list.value.length
list.value.push(...Array.from({ length: 10 }, (_, i) => `Album ${start + i + 1}`))
return list.value.length < 30
}
</script>
<template>
<div class="box">
<HuiInfiniteScroll :load="load">
<div v-for="item in list" :key="item" class="item">{{ item }}</div>
<template #loading>
<div class="tip"><HuiIcon name="loading" /> Loading more…</div>
</template>
<template #complete>
<div class="tip">
<HuiIcon name="check" /> Reached the end: {{ list.length }} entries total
</div>
</template>
</HuiInfiniteScroll>
</div>
</template>
<style scoped>
.box {
height: 300px;
overflow-y: auto;
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
.tip {
color: var(--hui-color-primary);
font-size: var(--hui-font-size-sm);
}
</style>
Loading errors
If load throws or rejects, loadError is emitted. There is no automatic retry, preventing repeated requests when an endpoint keeps failing. Show a Retry button and call triggerLoad() through a ref.
This example fails the first request for page 3. Scroll to the bottom, then click Retry:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInfiniteScroll } from '@nscode/handy-ui'
import type { InfiniteScrollExpose } from '@nscode/handy-ui'
const list = ref<string[]>([])
const scrollRef = ref<InfiniteScrollExpose | null>(null)
const errorMessage = ref('')
let failed = false
// A timer simulates an API: the first request for page 3 fails
const fetchPage = (offset: number) =>
new Promise<string[]>((resolve, reject) => {
window.setTimeout(() => {
if (offset === 20 && !failed) {
failed = true
reject(new Error('Network error: page 3 failed to load'))
return
}
resolve(Array.from({ length: 10 }, (_, i) => `Tracking number SF${1000 + offset + i}`))
}, 600)
})
const load = async () => {
const page = await fetchPage(list.value.length)
list.value.push(...page)
return list.value.length < 50
}
const retry = () => {
errorMessage.value = ''
scrollRef.value?.triggerLoad()
}
</script>
<template>
<div class="box">
<HuiInfiniteScroll ref="scrollRef" :load="load" @load-error="errorMessage = $event.message">
<div v-for="item in list" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
<div v-if="errorMessage" class="error">
{{ errorMessage }}
<HuiButton type="primary" variant="link" @click="retry">Retry</HuiButton>
</div>
</div>
</template>
<style scoped>
.box {
height: 300px;
overflow-y: auto;
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
.error {
padding: 12px 16px;
text-align: center;
color: var(--hui-color-danger);
}
</style>
Starting again
After load returns false, loading stops. When changing filters and replacing the displayed data, call reset() to clear the completed state. The component checks again and resumes loading.
First scroll to the completed state, then enter a surname such as 张 and press Enter:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInfiniteScroll, HuiInput, HuiSpace } from '@nscode/handy-ui'
import type { InfiniteScrollExpose } from '@nscode/handy-ui'
const surnames = ['张', '王', '李', '赵', '刘', '陈', '杨', '黄', '周', '吴']
const givenNames = ['伟', '芳', '娜', '敏', '静', '磊', '洋', '勇', '军', '杰']
const all = surnames.flatMap((s) => givenNames.map((g) => `${s}${g}`))
const keyword = ref('')
const list = ref<string[]>([])
const scrollRef = ref<InfiniteScrollExpose | null>(null)
const load = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 300))
const matched = all.filter((name) => name.includes(keyword.value))
list.value.push(...matched.slice(list.value.length, list.value.length + 10))
return list.value.length < matched.length
}
const search = () => {
list.value = []
scrollRef.value?.reset()
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiInput
v-model="keyword"
placeholder="Enter a surname and press Enter"
clearable
style="width: 200px"
@keyup.enter="search"
/>
<HuiButton type="primary" icon="search" @click="search">Search</HuiButton>
</HuiSpace>
<div class="box">
<HuiInfiniteScroll ref="scrollRef" :load="load">
<div v-for="item in list" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
</div>
</HuiSpace>
</template>
<style scoped>
.box {
height: 300px;
overflow-y: auto;
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
</style>
Page scrolling
Without a scrolling container, loading follows page scrolling. This example has 30 entries; scroll the page to load more.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll } from '@nscode/handy-ui'
const list = ref<string[]>([])
const load = async () => {
await new Promise((resolve) => window.setTimeout(resolve, 600))
const start = list.value.length
list.value.push(...Array.from({ length: 10 }, (_, i) => `Activity ${start + i + 1}`))
return list.value.length < 30
}
</script>
<template>
<HuiInfiniteScroll :load="load">
<div v-for="item in list" :key="item" class="item">{{ item }}</div>
</HuiInfiniteScroll>
</template>
<style scoped>
.item {
padding: 12px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
</style>
Error feedback and retry slot
The first attempt fails and retrying completes loading. The custom slot receives error and retry. The error area stays while retrying and is cleared or replaced only when the attempt settles, so keyboard focus remains on the retry button. The default retry button is marked unavailable while loading, and clicking it again does not start another load.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll, HuiButton } from '@nscode/handy-ui'
const attempts = ref(0)
const load = async () => {
attempts.value++
if (attempts.value === 1) throw new Error('Simulated network failure')
return false
}
</script>
<template>
<HuiInfiniteScroll :load="load" immediate>
<p>Request count: {{ attempts }}</p>
<template #error="{ error, retry }"
><HuiButton type="warning" @click="retry"
>{{ String(error) }}, click to retry</HuiButton
></template
>
</HuiInfiniteScroll>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| load | () => Promise<boolean | void> | - | Required loading function; resolving to false indicates no more data |
| distance | number | 0 | Distance in pixels before the content bottom at which loading starts |
| disabled | boolean | false | Whether loading is disabled |
| loading | boolean | false | Externally managed loading state; displays loading feedback and prevents new loads |
| immediate | boolean | false | Request once immediately after mounting |
Event names and retry order
Public declarations and emitted events use loadStart, loadComplete, and loadError. Only these names are emitted; there are no duplicate legacy events. Vue templates can use @load-start, @load-complete, and @load-error, which compile to camelCase listeners. Render functions use onLoadStart, onLoadComplete, and onLoadError.
Event order is unchanged: loadStart is emitted before load is called. After resolution, loadComplete receives hasMore (only false ends loading; undefined still means more data). A throw or rejection emits only loadError, preserving the original error object, and does not retry automatically. No start event is emitted while internally loading, disabled, externally loading, or complete. Failed loads can be retried manually; reset clears completion so loading can resume.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll } from '@nscode/handy-ui'
const eventControl = ref<InstanceType<typeof HuiInfiniteScroll>>()
const eventFailNext = ref(false)
const eventLog = ref<string[]>([])
const eventAttempts = ref(0)
const eventLoad = async () => {
eventAttempts.value++
if (eventFailNext.value) {
eventFailNext.value = false
throw new Error('Example load failed')
}
return false
}
const eventStart = () => {
eventLog.value.push('loadStart')
}
const eventComplete = (hasMore: boolean) => {
eventLog.value.push('loadComplete:' + hasMore)
}
const eventError = (error: Error) => {
eventLog.value.push('loadError:' + error.message)
}
const eventReset = () => {
eventControl.value?.reset()
eventLog.value = []
}
</script>
<template>
<div
class="infinite-scroll-events-demo"
style="display:flex;flex-direction:column;gap:var(--hui-spacing-3);max-width:520px"
>
<div style="display:flex;gap:var(--hui-spacing-3)">
<button class="infinite-event-load" @click="eventControl?.triggerLoad()">Load manually</button
><button class="infinite-event-reset" @click="eventReset">Reset completed state</button
><button class="infinite-event-fail" @click="eventFailNext = true">
Fail the next attempt
</button>
</div>
<span class="infinite-event-attempts">Calls: {{ eventAttempts }}</span>
<span class="infinite-event-log">{{ eventLog.join(' → ') || 'No events yet' }}</span>
<div style="height:140px;overflow:auto;border:1px solid var(--hui-border-color)">
<HuiInfiniteScroll
ref="eventControl"
:load="eventLoad"
@load-start="eventStart"
@load-complete="eventComplete"
@load-error="eventError"
><div style="min-height:220px;padding:var(--hui-spacing-3)">
Scrolling to the bottom also loads content. This example completes after one successful
load; reset it to try again.
</div></HuiInfiniteScroll
>
</div>
</div>
</template>
Events
| Event | Parameters | Description |
|---|---|---|
| loadStart | - | Emitted when loading starts |
| loadComplete | (hasMore: boolean) | Emitted after successful loading; hasMore is false when load resolves to false |
| loadError | (error: Error) | Emitted when load throws or rejects |
Slots
| Slot | Scope | Description |
|---|---|---|
| default | List content | |
| loading | Loading content; defaults to a spinner and localized loading text | |
| complete | Content shown when no more data remains; defaults to localized completed text | |
| error | Error content; defaults to a localized retry button |
Methods
Call through the component ref.
| Method | Parameters | Description | | ----------- | ---------- | --------------- | ----------------------------------------------------------------------------------------------- | | triggerLoad | - | Promise<void> | Manually trigger loading; does nothing while loading, disabled, externally loading, or complete | | reset | - | void | Clear the completed state and check whether loading is needed again |
Types
import type {
InfiniteScrollProps,
InfiniteScrollEmits,
InfiniteScrollExpose
} from '@nscode/handy-ui'
interface InfiniteScrollProps {
load: () => Promise<boolean | void>
distance?: number
disabled?: boolean
loading?: boolean
immediate?: boolean
}
interface InfiniteScrollEmits {
loadStart: []
loadComplete: [hasMore: boolean]
loadError: [error: Error]
}
interface InfiniteScrollExpose {
triggerLoad: () => Promise<void>
reset: () => void
}