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

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

相关推荐
小码吃趴菜几秒前
【无标题】
前端·chrome
毕设源码-朱学姐1 小时前
【开题答辩全过程】以 基于HTML5的购物网站的设计与实现为例,包含答辩的问题和答案
前端·html·html5
梦6501 小时前
CSS 元素垂直水平居中的 8 种方法
前端·css
We་ct1 小时前
LeetCode 68. 文本左右对齐:贪心算法的两种实现与深度解析
前端·算法·leetcode·typescript
ShoreKiten1 小时前
ctfshow-web316
运维·服务器·前端
前端 贾公子1 小时前
release-it 使用指南
前端·javascript
全栈技术负责人2 小时前
前端团队 AI Core Workflow:从心法到落地
前端·人工智能·状态模式
前端 贾公子2 小时前
深入浅出 CSS 属性:pointer-events: none
前端·css
曾几何时`2 小时前
二分查找(十)1146. 快照数组 pair整理
java·服务器·前端
夏河始溢3 小时前
一八二、webpack、grunt、gulp、rollup、parcel、vite 对比介绍
前端·webpack·gulp