vue 上拉加载实现

52 阅读1分钟
<ul class="list" ref="scrollBox">
	<li v-for="(item, index) in data" :key="index">
	     ...
	</li>
</ul>
<script>
	mounted() {
        // 监听如果页面发生滚动时
        this.$nextTick(() => {
            this.$refs.homeUl.addEventListener(
                'scroll',
                this.handleScroll,
                true
            );
        });
    },
    methods: {
		// 页面滑到底部需要调用的方法
        handleScroll() {
            // 下面这部分兼容手机端和PC端
            const scrollTop = this.$refs.scrollBox.scrollTop; // 滚动条的位置
            const windowHeitht = this.$refs.scrollBox.clientHeight; // 在页面上返回内容的可视高度
            const scrollHeight = this.$refs.scrollBox.scrollHeight; // 返回整个元素的高度(包括带滚动条的隐蔽的地方)
            // 是否滚动到底部的判断
            if (Math.round(scrollTop) + windowHeitht === scrollHeight) {
				//此处加载数据
            	this.loadData();
            }
        },
	}
</script>
<style>
.list{
	height: calc(100% - xxx);
    overflow: scroll;
}
</style>