PagedList Paged list
Combines paging requests, pull refresh, loading more and empty states. Provide a query function and an item slot. The component does not interpret business fields.
Import
Use <hui-paged-list> through uni-app easycom. Import public types from @nscode/handy-uni. Ordinary Vue 3 imports HuiPagedList from @nscode/handy-uni/web, or installs that entry's plugin.
The parent of container="self" must have a definite height. Keep pageSize at or below 50 when possible; the list is not virtualized.
Examples
Paging, filters and events
Return actual filter values from deps(). A changed array item reloads page one. Parent rerenders and new callback identities do not reset paging. Event output shows the server page, cumulative row count and scroll position.
<script setup lang="ts">
import { ref } from 'vue'
import type { PagedListError, PagedListLoaded, PagedListScroll } from '@nscode/handy-uni'
const onlyEven = ref(false)
const result = ref('Waiting for request')
const position = ref(0)
const records = Array.from({ length: 12 }, (_, index) => ({
id: index + 1,
name: `Record ${index + 1}`
}))
async function query(params: { page: number; pageSize: number }) {
const source = records.filter((row) => !onlyEven.value || row.id % 2 === 0)
const start = (params.page - 1) * params.pageSize
return { list: source.slice(start, start + params.pageSize), total: source.length }
}
function label(item: unknown) {
return (item as { name: string }).name
}
function loaded(info: PagedListLoaded) {
result.value = `loaded:page ${info.page},loaded ${info.list.length} rows, total ${info.total} rows`
}
function failed(info: PagedListError) {
result.value = `load-error:${info.scope},${String(info.error)}`
}
function scroll(info: PagedListScroll) {
position.value = info.scrollTop
}
</script>
<template>
<view>
<hui-button @click="onlyEven = !onlyEven">
{{ onlyEven ? 'Show all' : 'Even IDs only' }}
</hui-button>
<view style="height: 280px">
<hui-paged-list
:query="query"
:deps="() => [onlyEven]"
row-key="id"
:page-size="4"
:first-page="1"
@loaded="loaded"
@load-error="failed"
@scroll="scroll"
>
<template #header><text>Pull to refresh; scroll down for more</text></template>
<template #default="{ item, index }">
<view style="padding: 20px">{{ index + 1 }}. {{ label(item) }}</view>
</template>
</hui-paged-list>
</view>
<text aria-live="polite">{{ result }};scrollTop={{ position }}</text>
</view>
</template>
Manual initial load and custom states
With immediate=false, the initial state makes no request and shows neither loading nor empty content. Buttons demonstrate loading, request failure, retry, empty success and data success. retry() repeats the failed page; reload() starts from page one. Disabling pull gestures does not disable programmatic refresh().
<script setup lang="ts">
import { ref } from 'vue'
import type { PagedListExpose } from '@nscode/handy-uni'
const control = ref<PagedListExpose>()
const mode = ref<'error' | 'empty' | 'data'>('error')
async function query() {
await new Promise((resolve) => setTimeout(resolve, 80))
if (mode.value === 'error') throw Error('Demo network failure')
return { list: mode.value === 'empty' ? [] : [{ id: 1 }], hasMore: false }
}
function change(value: 'error' | 'empty' | 'data') {
mode.value = value
void control.value?.reload()
}
</script>
<template>
<view>
<hui-button @click="change('error')">Request error</hui-button>
<hui-button @click="change('empty')">Empty result</hui-button>
<hui-button @click="change('data')">Data result</hui-button>
<view style="height: 220px">
<hui-paged-list
ref="control"
:query="query"
row-key="id"
:immediate="false"
:refreshable="false"
empty-type="search"
empty-text="No matching records"
:load-more-props="{ finishedText: 'End of results' }"
>
<template #loading><text>Loading records</text></template>
<template #error="{ retry, error }">
<view>
<text>{{ String(error) }}</text>
<hui-button @click="retry">Retry current query</hui-button>
</view>
</template>
<template #empty="{ reload }">
<view><text>No matches</text><hui-button @click="reload">Reload</hui-button></view>
</template>
<template #default="{ index }"
><view>Result {{ index + 1 }}</view></template
>
</hui-paged-list>
</view>
</view>
</template>
Methods and local list updates
Request methods return Promise<boolean>: true only when that request succeeds and remains current. Failure, duplicate loading, a finished list and stale results return false. refresh() keeps existing rows until success; reload() clears them immediately. Local updates never call an API or emit loaded.
Deletion first opens a confirmation dialog. List changes dismiss stale confirmation, and the confirm handler verifies both the list snapshot and target again. In an application, confirm first, call the delete API, then removeItem() or refresh after success.
<script setup lang="ts">
import { ref, watch } from 'vue'
import type { PagedListExpose } from '@nscode/handy-uni'
interface Row {
id: number
name: string
}
const control = ref<PagedListExpose<Row>>()
const result = ref('')
const confirmVisible = ref(false)
let nextId = -1
let target: Row | undefined
let snapshot: readonly Row[] | undefined
const source = Array.from({ length: 10 }, (_, index) => ({
id: index + 1,
name: `Server record ${index + 1}`
}))
async function query(params: { page: number; pageSize: number }) {
const start = (params.page - 1) * params.pageSize
return { list: source.slice(start, start + params.pageSize), total: source.length }
}
function label(item: unknown) {
return (item as Row).name
}
async function request(method: 'reload' | 'refresh' | 'loadMore' | 'retry') {
result.value = `${method}:${await control.value?.[method]()}`
}
function prepend() {
control.value?.prependItem({ id: nextId--, name: 'Local new record' })
}
function updateFirst() {
const row = control.value?.list[0]
if (row) control.value?.updateItem(row.id, { ...row, name: 'Updated locally' })
}
function cancelRemove() {
confirmVisible.value = false
target = undefined
snapshot = undefined
}
function askRemove() {
target = control.value?.list[0]
snapshot = control.value?.list
confirmVisible.value = !!target
}
function confirmRemove() {
const row = target
const valid = row && snapshot && control.value?.list === snapshot && snapshot.includes(row)
cancelRemove()
if (valid && row) control.value?.removeItem(row.id)
}
watch(() => control.value?.list, cancelRemove, { flush: 'sync' })
</script>
<template>
<view>
<hui-button @click="request('reload')">reload</hui-button>
<hui-button @click="request('refresh')">refresh</hui-button>
<hui-button @click="request('loadMore')">loadMore</hui-button>
<hui-button @click="request('retry')">retry</hui-button>
<hui-button @click="prepend">prependItem</hui-button>
<hui-button @click="updateFirst">updateItem</hui-button>
<hui-button :disabled="!control?.list.length" @click="askRemove">Delete first</hui-button>
<hui-button @click="() => control?.scrollTo(0)">scrollTo(0)</hui-button>
<view style="height: 260px">
<hui-paged-list ref="control" :query="query" row-key="id" :page-size="3">
<template #default="{ item }"
><view style="padding: 20px">{{ label(item) }}</view></template
>
</hui-paged-list>
</view>
<text
>{{ result }};Current {{ control?.list.length }} rows, total {{ control?.total }},{{
control?.loading
}},finished={{ control?.finished }}</text
>
<hui-dialog
v-model:visible="confirmVisible"
title="Delete first record"
message="Remove the selected 1 record from the current local list? No delete API will be called."
show-cancel-button
@confirm="confirmRemove"
@cancel="cancelRemove"
@closed="cancelRemove"
/>
</view>
</template>
Ordinary Vue page scrolling
container=page works only in ordinary Vue. uni-H5, WeChat and App-vue use self. A uni page that scrolls the page itself should use usePaging() and connect native refresh and reach-bottom lifecycle in the page.
<script setup lang="ts">
const query = async () => ({
list: Array.from({ length: 6 }, (_, index) => ({ id: index + 1 })),
hasMore: false
})
</script>
<template>
<view>
<hui-paged-list :query="query" row-key="id" container="page">
<template #default="{ index }"
><view style="padding: 40px">Item {{ index + 1 }}</view></template
>
</hui-paged-list>
</view>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
query | UniQuery<PagingParams, unknown> | Required | Receives { page, pageSize } and { signal }. |
normalize | UniPageNormalizer<unknown> | — | Converts the response to { list, total?, hasMore? }; otherwise uses the configured global normalizer. |
pageSize | number | 20 | Fixed at creation; 50 or fewer is recommended. |
firstPage | number | 1 | First server page, including 0; fixed at creation. |
rowKey | string | ((row: unknown) => PropertyKey) | — | Rendering identity and deduplication key. Without it, warns and keeps all rows using index keys. |
deps | () => readonly unknown[] | — | Compares array items with Object.is and reloads on changed values. |
immediate | boolean | true | Requests page one on creation. Set false for manual loading. |
refreshable | boolean | true | Enables pull gestures; methods remain callable. |
container | 'self' | 'page' | 'self' | page is ordinary Vue only; uni warns in development and uses self. |
emptyText | string | — | Empty description; an explicit empty string is preserved. |
emptyType | EmptyType | 'empty' | empty, search, error or network. |
loadMoreProps | PagedListLoadMoreProps | — | Explicit idleText, loadingText, finishedText and errorText; omitted values use the locale. |
customClass | string | '' | Class added to the root. |
customStyle | string | CSSProperties | — | Style added to the root. |
query, normalize and rowKey read current props when called; replacing functions does not reload. Put actual nested filter values in deps(). Recreate the component to change pageSize or firstPage.
Events
| Event | Arguments | Description |
|---|---|---|
loaded | (info: PagedListLoaded) | Current request succeeded. list is a shallow cumulative array snapshot; page is this request's server page. |
load-error | (info: PagedListError) | Current request failed; scope is first, refresh or more. |
scroll | (info: PagedListScroll) | Forwards { scrollTop } in px. |
Canceled, unmounted and replaced requests emit no result events. The loaded array is copied; its row objects retain identity.
Slots
| Slot | Scope | Description |
|---|---|---|
default | { item, index } | Item content; the component owns iteration and keys. |
header | — | Scrolls above the items. |
empty | { reload } | Replaces Empty after a successful empty result. |
error | { retry, error } | Request error when no rows are available. |
loading | — | Initial loading; defaults to Loading. |
A failed next page or refresh with existing data keeps the rows and offers retry in LoadMore. Before the first request, no empty state is displayed. A retry without data displays loading.
Methods
| Method or readonly state | Signature / type | Description |
|---|---|---|
reload | () => Promise<boolean> | Clears the list and requests page one. |
refresh | () => Promise<boolean> | Requests page one while retaining existing data until success. |
loadMore | () => Promise<boolean> | Requests the next page; false while loading, finished or waiting to retry a failed next page. |
retry | () => Promise<boolean> | Repeats the failed page; false without an error. |
removeItem | (key: PropertyKey) => void | Removes a local row by rowKey and reduces total when supplied; user actions require confirmation first. |
updateItem | (key: PropertyKey, row: T) => void | Replaces a local row without requesting. |
prependItem | (row: T) => void | Prepends locally with rowKey deduplication; does not increase server total. |
scrollTo | (top: number) => void | Scrolls its own container in self mode, or the page in ordinary Vue page mode; px. |
list | readonly T[] | Readonly cumulative rows; use methods to change them. |
total | number | undefined | Server total, or undefined if omitted. |
loading | PagingLoading | none, first, refresh or more. |
finished | boolean | Whether all rows for the current query are loaded. |
Without rowKey, removeItem and updateItem cannot identify rows and do nothing.
Types
Import PagedListProps, PagedListEmits<T>, PagedListExpose<T>, PagedListLoadMoreProps, PagedListLoaded<T>, PagedListError, PagedListScroll and PagedListSlots<T> from @nscode/handy-uni.
interface PagedListLoadMoreProps {
idleText?: string
loadingText?: string
finishedText?: string
errorText?: string
}
interface PagedListLoaded<T = unknown> {
list: T[]
page: number
total?: number
}
Platform notes
| Platform | Behavior |
|---|---|
| WeChat / App-vue / uni-H5 | self uses native scroll-view refresh. page warns and falls back to self. |
| Ordinary Vue | self uses its container; page uses document scrolling and takes over vertical pull only at the top. |
| All | Explicit prop bindings and fixed named slots. No argumentless v-bind/v-on or virtualization. |
Duplicate row keys warn in development and keep the first occurrence. Missing rowKey also warns. New requests and unmount abort the old signal. Even when physical cancellation is unavailable, stale results cannot write back. See examples/uni-demo/smoke/PagedList.md for device checks; unsampled devices remain pending.