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

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

相关推荐
im_AMBER5 分钟前
react-i18next 国际化支持
前端·react.js·前端框架
文心快码BaiduComate7 分钟前
Comate 3月全新升级:全新Plan模式、Explore Subagent深度检索能力增强
前端·后端·程序员
Lsx_7 分钟前
前端发版后页面白屏?一套解决用户停留旧页面问题的完整方案
前端·javascript·掘金·日新计划
方安乐8 分钟前
pnpm与npm混用为什么会报错?
前端·npm·node.js
什么时候星期五11 分钟前
node版本升级后,项目跑不起来
前端·node.js
Forever7_13 分钟前
扫码枪卡顿有效解决方案
前端
aZhe的全栈知识分享14 分钟前
OpenClaw(龙虾)太难装?这份保姆级教程让你 3 分钟搞定
前端·人工智能·后端
sinat_2554878122 分钟前
保存 Object 数组
java·服务器·前端
炽烈小老头27 分钟前
函数式编程范式(二)
前端·typescript
J2虾虾30 分钟前
通过Web界面来访问和操作MySQL数据库的开源项目
前端·数据库·mysql