v-infinitescroll 指令
介绍
v-infinitescroll
指令用于实现无限滚动功能,当滚动到底部时触发加载更多数据。
使用方法
将 v-infinitescroll
指令添加到页面数据请求过多,滚动到容器底部,再次加载:
vue
<template>
<div v-infinitescroll="scrollOptions" class="scroll-container">
<div v-for="n in count" :key="n" class="scroll-item">项目 {{ n }}</div>
</div>
</template>
// 无限滚动配置 const scrollOptions = { handler: loadMore, distance: 50, throttle: 1000 }
项目 1
项目 2
项目 3
项目 4
项目 5
项目 6
项目 7
项目 8
项目 9
项目 10
项目 11
项目 12
项目 13
项目 14
项目 15
项目 16
项目 17
项目 18
项目 19
项目 20
查看代码
vue
<template>
<div v-infinitescroll="scrollOptions" class="scroll-container">
<div v-for="n in count" :key="n" class="scroll-item">项目 {{ n }}</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { vInfiniteScroll } from '@cp-vuedir/core'
import { Message } from '@arco-design/web-vue'
const count = ref(20)
// 最简单的加载方法
const loadMore = () => {
count.value += 10
Message.success('加载更多数据中')
}
// 无限滚动配置
const scrollOptions = {
handler: loadMore,
distance: 50,
throttle: 1000
}
</script>
<style scoped>
.scroll-container {
height: 400px;
overflow-y: auto;
padding: 16px;
border: 1px solid #e2e8f0;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.scroll-item {
padding: 12px 16px;
margin: 8px 0;
background: var(--vp-c-bg-soft);
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
color: var(--vp-c-text-1);
font-size: 14px;
line-height: 1.5;
cursor: pointer;
}
.scroll-item:hover {
transform: translateX(4px);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
background: #f1f5f9;
}
.scroll-container::-webkit-scrollbar {
width: 8px;
}
.scroll-container::-webkit-scrollbar-track {
background: var(--vp-c-bg);
border-radius: 4px;
}
.scroll-container::-webkit-scrollbar-thumb {
background: var(--vp-button-bg);
border-radius: 4px;
}
.scroll-container::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
/* 加载提示动画 */
.loading-dots::after {
content: '';
display: inline-block;
animation: dotFlashing 1s infinite linear;
}
@keyframes dotFlashing {
0% {
content: '.';
}
33% {
content: '..';
}
66% {
content: '...';
}
100% {
content: '.';
}
}
</style>
API
属性名 | 说明 | 类型 | 是否必选 | 默认值 |
---|---|---|---|---|
handler | 滚动到底部时触发的回调函数 | Function | 用户自己定义 | |
distance | 触发加载的距离阀值,即距离底部多少像素时开始加载更多数据 | Number | 0 | |
throttle | 节流时间,即每隔多少毫秒触发一次回调函数 | Number | 200 |
注意事项
注意
- 容器高度设定:确保滚动容器具有固定的高度,并且设置 overflow-y: auto 或 overflow-y: scroll,这是无限滚动能够正常工作的前提。
- 回调函数定义:
handler
回调函数必须定义,并且在该函数中实现加载更多数据的逻辑。确保函数内部不会引起无限循环或重复加载。 - 距离阈值:
distance
参数设置要合理,既不能太大导致用户滚动很久才加载,也不能太小导致刚滚动就加载,影响用户体验。 - 节流设置:
throttle
参数用于控制滚动事件触发的频率,防止短时间内多次触发加载函数。根据实际滚动速度和性能要求进行调整。