封装一个自己的loadingMore组件

写过小程序或者uni-app的前端朋友们,肯定了解过onReachBottom触底加载更多函数,当页面滑动到最底部的时候加载更多内容。

现有一需求:封装一个组件符合高内聚、低耦合原则,实现触底加载更多回调。

技术选型:调研最快捷简单的实现方式是使用H5 的IntersectionObserver API,且各大浏览器都早已做了兼容。

其原理是监听元素是否出现在视窗内,当元素可见的时候触发回调函数

js 复制代码
const intersectionObserver = new IntersectionObserver((entries) => {
  // 如果 intersectionRatio 为 0,则目标在视野外,
  // 我们不需要做任何事情。
  if (entries[0].intersectionRatio <= 0) return;

  loadItems(10);
  console.log("Loaded new items");
});
// 开始监听
intersectionObserver.observe(document.querySelector(".scrollerFooter"));

代码封装:

xml 复制代码
<template>
    <view id="showMoreData" class="load-more">
        加载更多...
    </view>
</template>
<script>
export default {
    data() {
        return {
            intersectionObsever: null
        }
    },
    props: {
        loadStatus: {
            type: String,
            default: 'loadmore' //loading、loadmore、nomore
        }
    },
    methods: {
        listenViewInDevice() {
            let me = this;
            this.intersectionObsever= new IntersectionObserver(function (entries) {
                if (entries[0].intersectionRatio > 0) {
                    if(me.loadStatus == 'loadmore') {
                        me.$emit('loadMore')
                    }
                }
            });
            this.intersectionObsever.observe(document.querySelector("#showMoreData"));
        },
    },
    mounted() {
        this.listenViewInDevice();
    },
    beforeDestroy(){
        this.intersectionObsever.disonnect();
    },
    activated() {
        this.listenViewInDevice();
    },
    deactivated() {
        this.intersectionObsever.disonnect();
    }
}
</script>
<style scoped lang='scss'>
.load-more {
    width: 100%;
    display: flex;
    justify-content: 'center';
    height: 80rpx;
}
</style>

为避免keep-alive导致页面被缓存,使用activated和deactivated来创建和销毁实例。

觉得文章对您有帮助的话,麻烦点个赞吧,谢谢~🙏

相关推荐
oooo_z4 分钟前
美股历史K线数据API接口选型指南:iTick覆盖1分钟到月线全周期
服务器·前端·javascript
今日无bug19 分钟前
从 0 到 1 搭建端侧 AI 项目:DeepSeek-R1 + WebGPU + React + TS + Tailwind 全栈笔记
前端·react.js·typescript
mmsx21 分钟前
MapLibre 实战 08|GPS 点漂了几百米才被发现:GCJ-02 纠偏原理与"转两次"陷阱
android·前端
李高钢23 分钟前
Python Flask 框架入门:从零搭建你的第一个 Web 应用
前端·python·flask
特立独行的猫A25 分钟前
用仓颉语言写 Coding Agent:cjh 是怎么实现的
前端
特立独行的猫A27 分钟前
cjh:基于华为仓颉语言的原生 Coding Agent Harness 实践与设计思考
前端
mONESY32 分钟前
LangChain 结构化输出三兄弟:ToolCall、OutputParser、withStructuredOutput 彻底讲透
javascript
晚安日记wanna34 分钟前
大文件分片上传的五层追问从 Blob 切片到秒传与弱网容错
前端·面试
Htr_38 分钟前
Anysite.io 使用指南:把整个 Web 变成 AI 智能体的数据库
前端·数据库·人工智能
知兀41 分钟前
【前端】受控和非受控组件
前端·javascript·react