vue3(上拉/触底)加载更多方式
作者:wopmni
本文详细解析了Vue3实现触底加载更多功能的核心原理,包括监听窗口滚动事件及获取滚动相关属性,并总结了页面代码实现要点,适合前端开发者参考学习
vue3(上拉/触底)加载更多
核心原理
监听页面的滚动事件
window.addEventListener('scroll', function)
获取可视窗口高度,滚动高度,滚动条高度
document.documentElement.clientHeight; // 获取可视高度 document.documentElement.scrollTop // 获取滚动高度 document.documentElement.scrollHeight // 获取滚动条高度
页面代码
<template>
<div class="container">
<ul>
<li class="item" v-for="(item, index) in dataList" :key="index">{{ item }}</li>
</ul>
</div>
</template>
<script setup>
import { reactive } from 'vue';
const dataList = reactive([1, 2, 3, 4])
// 节流方法
const throttle = (func, delay) => {
let timer = null;
return function () {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, arguments);
timer = null
}, delay)
}
}
}
// 触底函数
const onReachBottom = () => {
window.addEventListener('scroll', throttle(onBottom, 200))
}
// 触底相应函数
const onBottom = () => {
// 获取可视高度
let clientHeight = document.documentElement.clientHeight;
// 获取滚动高度
let scrollTop = document.documentElement.scrollTop
// 滚动条高度
let scrollHeight = document.documentElement.scrollHeight
if (clientHeight + scrollTop > scrollHeight) {
console.log('触底了')
dataList.push(dataList.length + 1)
}
}
onReachBottom()
</script>
<style lang="scss" scoped>
.item {
margin-top: 20px;
width: 200px;
height: 200px;
font-size: 30px;
text-align: center;
line-height: 200px;
background-color: hotpink;
}
</style>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
