InfiniteScroll 无限滚动
列表滚到底部时自动加载下一页,用于“滚动加载更多”的长列表。
引入
import { HuiInfiniteScroll } from '@nscode/handy-ui'
基础用法
把列表放进 HuiInfiniteScroll,再把它放进一个有高度、overflow: auto 的滚动容器。load 返回 Promise,加载完成后 resolve;resolve 为 false 表示没有更多数据,之后显示“没有更多了”,不再加载。下面每次加载 10 条,共 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 = ['提交了报销单', '评论了你的文章', '关注了你', '更新了项目进度']
// 这里用定时器代替真实的接口请求
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>
挂载时如果列表末尾已经在视口内(例如一开始没有数据),会自动开始加载;内容不满一屏时会连续加载,直到填满容器或 load 返回 false。
提前触发
distance 是距离内容底部多少像素时开始加载,默认 0(滚到底才加载)。设为 200 时,还差 200px 滚到底就会加载下一页,用户不容易看到“加载中”。
左右两个列表一样,只有 distance 不同,分别往下滚看看:
<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]}门店 ${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(默认):已加载 {{ listA.length }} 条</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 }} 条</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。immediate 用在一开始就有数据、列表末尾不在视口内,但仍想在挂载后马上请求一次的场景,例如先显示缓存的 20 条,挂载后立刻拉下一页。
左右两个列表都带着 20 条初始数据,右边加了 immediate,挂载后马上多加载了 10 条:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInfiniteScroll, HuiSpace } from '@nscode/handy-ui'
const makePage = (start: number) =>
Array.from({ length: 10 }, (_, i) => `文章 ${start + i + 1}:本周技术周报`)
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">不加 immediate:{{ listA.length }} 条</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 }} 条</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 为 true 时不加载。loading 为 true 时显示“加载中”,同样不触发加载,适合加载状态由外部管理的场景。两者改回 false 后,如果列表末尾在视口内,会立即加载。
打开任意一个开关后把列表滚到底,不会再加载;关掉后马上接着加载:
<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) => `待办事项 ${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="外部加载中(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>
加载事件
每次开始加载触发 loadStart,加载成功触发 loadComplete,参数 hasMore 表示还有没有下一页。下面共 30 条,最后一次的 hasMore 是 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) => `商品评价 ${start + i + 1}:物流很快`))
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>最近的事件:{{ events.join(',') || '还没有' }}</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>
自定义加载状态
loading 插槽替换“加载中...”,complete 插槽替换“没有更多了”。下面共 30 条,滚到底能看到两个插槽的效果:
<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) => `相册 ${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" /> 正在拼命加载……</div>
</template>
<template #complete>
<div class="tip"><HuiIcon name="check" /> 已经到底了,共 {{ list.length }} 条</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>
加载出错
load 抛错或 reject 时触发 loadError,不会自动重试,避免接口一直报错时无限请求。可以显示一个“重试”按钮,点击时通过 ref 调用 triggerLoad()。
下面模拟第 3 页第一次请求失败,滚到底后点“重试”:
<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
// 用定时器模拟接口:第 3 页第一次请求失败
const fetchPage = (offset: number) =>
new Promise<string[]>((resolve, reject) => {
window.setTimeout(() => {
if (offset === 20 && !failed) {
failed = true
reject(new Error('网络异常,第 3 页加载失败'))
return
}
resolve(Array.from({ length: 10 }, (_, i) => `快递单号 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">重试</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>
重新开始
load 返回过 false 以后不会再加载。切换筛选条件、清空数据重新加载时,调用 reset() 清除“没有更多了”的状态,组件会重新检查并开始加载。
先滚到底看到“没有更多了”,再输入姓氏(如“张”)按回车:
<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="输入姓氏后按回车"
clearable
style="width: 200px"
@keyup.enter="search"
/>
<HuiButton type="primary" icon="search" @click="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>
页面滚动
不包滚动容器时,跟随整个页面的滚动加载。下面共 30 条,把页面往下滚就会接着加载。
<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) => `动态 ${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 与 retry。重试期间错误区保留,加载有了结果才清掉或换成新的错误,用键盘点重试时焦点一直在按钮上;默认的重试按钮在加载中标为不可用,再点不会重复加载。
<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('模拟网络失败')
return false
}
</script>
<template>
<HuiInfiniteScroll :load="load" immediate>
<p>请求次数:{{ attempts }}</p>
<template #error="{ error, retry }"
><HuiButton type="warning" @click="retry">{{ String(error) }},点击重试</HuiButton></template
>
</HuiInfiniteScroll>
</template>
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| load | () => Promise<boolean | void> | - | 加载函数,必填。resolve 为 false 表示没有更多数据 |
| distance | number | 0 | 距离内容底部多少像素时提前触发加载 |
| disabled | boolean | false | 是否禁用加载 |
| loading | boolean | false | 外部的加载状态。为 true 时显示“加载中”,并且不触发加载 |
| immediate | boolean | false | 挂载后是否立即加载一次 |
加载事件命名与重试顺序
公开声明和实际发射统一为 loadStart、loadComplete、loadError,只发新名,不双发旧事件。Vue模板仍可写 @load-start、@load-complete、@load-error,由编译器解析为驼峰监听;渲染函数使用 onLoadStart、onLoadComplete、onLoadError。
原时序保持:开始先通知loadStart,再调用load;resolve后loadComplete首参为hasMore(只有false表示结束,undefined仍有更多);抛错/reject只通知loadError并保留原错误对象,不自动重试。加载中、禁用、外部loading和已完成时不发开始事件。失败后可手动重试,reset可清掉完成状态重新加载。
<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('示例加载失败')
}
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()">手动加载</button
><button class="infinite-event-reset" @click="eventReset">重置完成状态</button
><button class="infinite-event-fail" @click="eventFailNext = true">下次失败</button>
</div>
<span class="infinite-event-attempts">调用:{{ eventAttempts }}</span>
<span class="infinite-event-log">{{ eventLog.join(' → ') || '尚无事件' }}</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)">
滚动到内容底部也可加载;本例一次成功后即结束,重置可再试。
</div></HuiInfiniteScroll
>
</div>
</div>
</template>
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| loadStart | - | 开始加载时触发 |
| loadComplete | (hasMore: boolean) | 加载成功时触发,load resolve 为 false 时 hasMore 为 false |
| loadError | (error: Error) | load 抛错或 reject 时触发 |
Slots
| 插槽 | 说明 |
|---|---|
| default | 列表内容 |
| loading | 加载中显示的内容,默认是转圈加“加载中...”(随语言) |
| complete | 没有更多数据时显示的内容,默认是“没有更多了”(随语言) |
| error | 加载失败时显示,默认按钮“加载失败,点击重试” |
方法
通过组件的 ref 调用。
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| triggerLoad | - | Promise<void> | 手动触发一次加载。加载中、禁用、外部 loading 或已加载完时不执行 |
| reset | - | void | 清除“没有更多了”的状态,并重新检查是否需要加载 |
类型
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
}