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

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

相关推荐
笨笨饿12 分钟前
#121_图传中的H.364编码与MP4的联系
linux·运维·前端·单片机·嵌入式硬件·面试·职场和发展
柒和远方20 分钟前
V079: Milvus 向量数据库:AI 日记本的三组件部署、集合字段建模与余弦索引
javascript·sql
水獭比特22 分钟前
Anthropic Files / Skills 迁移:Workspace 不是租户隔离,API Key 也不是用户身份
javascript
默_笙33 分钟前
☕ 我给 TS 类型做了台"瘦身手术",还顺手用 Docker 起了个 MySQL
前端·javascript
leoZ2311 小时前
AI+前端提效- 06 AI辅助调试排错:前端报错、白屏、兼容问题极速定位
前端·人工智能·chatgpt·状态模式·超分辨率重建·openvino·dreamfusion
ji_shuke2 小时前
Vue 3 使用 History 哨兵和 popstate 拦截浏览器返回
前端·javascript·vue.js·history·哨兵·popstate
名字还没想好☜2 小时前
Prometheus 告警实战:写 alerting rules、用 Alertmanager 做路由分组与抑制
运维·前端·javascript·docker·kubernetes·prometheus
郭邯2 小时前
从零撸了一个 HTML 实体编解码工具,顺便聊聊我和 AI 结对编程的日常
前端
樊小肆2 小时前
DeepSeeker-Code源码导读12-Hooks四引擎
前端·人工智能·agent
xm_xm_xm_13 小时前
TypeScript 7 个 核心特性
前端·typescript