封装一个自己的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来创建和销毁实例。

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

相关推荐
之歆9 分钟前
Day03_HTML 列表、表格、表单完整指南(下)
android·javascript·html
焦糖玛奇朵婷11 分钟前
解锁扭蛋机小程序的五大优势
java·大数据·服务器·前端·小程序
SwJieJie22 分钟前
windsurf的配置和项目规则、工作流、agent技巧使用
前端
白日梦想家68131 分钟前
从基础入手,分清一次性定时器与永久定时器
前端
李白的天不白32 分钟前
读到数据为undefind是的几种情况
开发语言·javascript·ecmascript
AIwork4me1 小时前
别再把 RAG 当知识库:用 AutoClaw 搭一套会进化的 Karpathy LLM Wiki
前端
彩票管理中心秘书长1 小时前
Git 归档与补丁命令大全(完整详解版)
前端
RePeaT1 小时前
【Nginx】前端项目部署与反向代理实战指南
前端·nginx
索木木2 小时前
ShortCut MoE模型分析
前端·html
MXN_小南学前端2 小时前
Vue3 + Spring Boot 工单系统实战:用户反馈和客服处理的完整闭环(提供gitHub仓库地址)
前端·javascript·spring boot·后端·开源·github