搜索结果列表页面开发
This commit is contained in:
68
src/components/ScrollContainer/index.vue
Normal file
68
src/components/ScrollContainer/index.vue
Normal file
@@ -0,0 +1,68 @@
|
||||
<template>
|
||||
<div ref='ScrollContainer'>
|
||||
<slot></slot>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang='ts' setup>
|
||||
import { onMounted, onUnmounted, ref } from 'vue';
|
||||
import throttle from 'lodash/throttle';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
loading?: boolean // 加载内容中
|
||||
finished?: boolean // 完成加载
|
||||
bottom?: number // 底部预留空间
|
||||
disabled?: boolean
|
||||
}>(), {
|
||||
bottom: 200
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'touch-bottom': [] // 滚动触底时触发
|
||||
'change': [obj: Object] // 容器内容变化时触发
|
||||
}>();
|
||||
|
||||
const ScrollContainer = ref();
|
||||
const observer = ref();
|
||||
|
||||
const onScroll = throttle(() => {
|
||||
if (props.loading || props.finished || props.disabled) return;
|
||||
// 滚动高度
|
||||
const scrollTop =
|
||||
document.documentElement.scrollTop + document.body.scrollTop;
|
||||
// 窗口高度
|
||||
const wHeight =
|
||||
document.documentElement.clientHeight || document.body.clientHeight;
|
||||
// 页面高度
|
||||
const documentHeight =
|
||||
document.documentElement.scrollHeight || document.body.scrollHeight;
|
||||
|
||||
if (Math.abs(wHeight + scrollTop - documentHeight) <= props.bottom) {
|
||||
emit('touch-bottom');
|
||||
}
|
||||
}, 200);
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('scroll', onScroll);
|
||||
observer.value = new MutationObserver((mutations) => {
|
||||
// 窗口高度
|
||||
const wHeight = document.documentElement.clientHeight || document.body.clientHeight;
|
||||
emit('change', {
|
||||
// 事件源
|
||||
mutations,
|
||||
// 是否覆盖第一屏
|
||||
cover: ScrollContainer.value.clientHeight + ScrollContainer.value.offsetTop >= wHeight
|
||||
});
|
||||
});
|
||||
// 开始监听元素变化
|
||||
observer.value.observe(ScrollContainer.value, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('scroll', onScroll);
|
||||
observer?.value?.disconnect();
|
||||
});
|
||||
</script>
|
||||
Reference in New Issue
Block a user