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,不會自動重試,避免 API 持續回報錯誤時無限請求。可以顯示一個“重試”按鈕,點擊時透過 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() 清除“沒有更多了”的狀態,元件會重新檢查並開始載入。
先滾到底看到“沒有更多了”,再輸入姓氏(如“张”)按 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"
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
}