Monitor the page to slide to the bottom
IntersectionObserver
Listening for bottoming out in Vue can be IntersectionObserver
achieved using . IntersectionObserver
is an API that can asynchronously observe the state of a target element and its ancestors or viewport intersections. IntersectionObserver's callback function is triggered when the target element enters or exits the viewport.
Here's an example of listening for bottoming out:
<template>
<div class="container" ref="container">
<!-- 这里是数据列表 -->
</div>
</template>
<script>
export default {
data() {
return {
observer: null,
}
},
mounted() {
// 创建 IntersectionObserver 实例
this.observer = new IntersectionObserver(this.handleObserve, {
root: null,
rootMargin: '0px',
threshold: 1.0,
});
// 监听容器底部
this.observer.observe(this.$refs.container.lastChild);
},
methods: {
handleObserve(entries) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// 滚动到底部触发加载更多
this.loadMoreData();
}
});
},
loadMoreData() {
// 加载更多数据的逻辑
},
},
};
</script>
Create an IntersectionObserver instance in the mounted hook function and monitor the elements at the bottom of the container. In the handleObserve callback function, it is judged whether the current element is visible, and if it is visible, the logic of loading more data is triggered.
scroll event listener
The method of monitoring the page sliding to the bottom in Vue is as follows:
- Create an
scroll
event listener and bind the event to the root element (window
ordocument.body
).
mounted() {
window.addEventListener('scroll', this.handleScroll)
}
- In the event processing function
handleScroll
, determine the condition that the page scrolls to the bottom, and if the condition is true, execute the custom eventscroll-to-bottom
.
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
const clientHeight = document.documentElement.clientHeight || window.innerHeight
if (scrollTop + clientHeight >= scrollHeight) {
this.$emit('scroll-to-bottom')
}
}
}
- In components that need to monitor scrolling to the bottom, use
$on
the method to monitor custom eventsscroll-to-bottom
and perform corresponding operations.
<template>
<div>
<div v-for="item in list" :key="item.id">{
{ item.text }}</div>
</div>
</template>
<script>
export default {
data() {
return {
list: []
}
},
mounted() {
this.loadMore()
this.$on('scroll-to-bottom', this.loadMore)
},
methods: {
loadMore() {
// TODO: 加载更多数据
}
}
}
</script>