上拉刷新,触底加载

  • 原生js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
document.addEventListener('DOMContentLoaded', function() {
const content = document.getElementById('content');
let isLoading = false;
// 上拉刷新
function handlePullToRefresh() {
if (content.scrollTop === 0 && !isLoading) {
isLoading = true;
// 模拟数据加载
setTimeout(() => {
// 插入新内容到顶部
const newContent = document.createElement('div');
newContent.textContent = 'New Content';
content.insertBefore(newContent, content.firstChild);
isLoading = false;
}, 1000);
}
}
// 触底加载
function handleLoadMore() {
if (content.scrollHeight - content.scrollTop <= content.clientHeight && !isLoading) {
isLoading = true;
// 模拟数据加载
setTimeout(() => {
// 插入新内容到底部
const newContent = document.createElement('div');
newContent.textContent = 'More Content';
content.appendChild(newContent);
isLoading = false;
}, 1000);
}
}
// 监听滚动事件,触发上拉刷新和触底加载
content.addEventListener('scroll', function() {
handlePullToRefresh();
handleLoadMore();
});
});
  • vue3 setup 组合式api 写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<template>
<div id="content" @scroll="handleScroll">
<div v-for="item in items" :key="item">{{ item }}</div>
</div>
</template>

<script>
import { ref } from 'vue';

export default {
setup() {
const items = ref([1, 2, 3, 4, 5]);
let isLoading = false;

// 上拉刷新
function handlePullToRefresh(e) {
if (e.target.scrollTop === 0 && !isLoading) {
isLoading = true;
setTimeout(() => {
items.value.unshift('New Content');
isLoading = false;
}, 1000);
}
}

// 触底加载
function handleLoadMore(e) {
if (e.target.scrollHeight - e.target.scrollTop <= e.target.clientHeight && !isLoading) {
isLoading = true;
setTimeout(() => {
items.value.push('More Content');
isLoading = false;
}, 1000);
}
}

// 处理滚动事件
function handleScroll(e) {
handlePullToRefresh(e);
handleLoadMore(e);
}

return {
items,
handleScroll
};
}
};
</script>