UniApp Vue3 页面触底事件 onReachBottom 报错解决方法
在 UniApp 中,使用 Vue3 开发页面时,触底事件 'onReachBottom' 可能会报错。这是因为在 Vue3 中,'onReachBottom' 事件已经被废弃,需要使用新的 API 来实现。
解决方法如下:
1. 使用新的 API:
在 Vue3 中,可以使用新的 API 来实现页面触底事件。可以使用 IntersectionObserver API 来监听页面底部元素是否出现在视口中。具体实现方式可以参考以下代码:
<template>
<div ref="bottom">底部内容</div>
</template>
<script>
import { onMounted, onUnmounted } from 'vue'
export default {
setup() {
const bottomRef = ref(null)
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
console.log('到达页面底部')
}
})
onMounted(() => {
observer.observe(bottomRef.value)
})
onUnmounted(() => {
observer.disconnect()
})
return {
bottomRef
}
}
}
</script>
在模板中,使用 ref 指令将底部元素绑定到 bottomRef 变量上,在 setup 函数中创建 IntersectionObserver 实例,并使用 onMounted 和 onUnmounted 钩子函数来启动和停止观察器。
2. 使用原生的 onReachBottom 事件:
如果要继续使用 'onReachBottom' 事件,可以在页面配置文件(如 pages/index/index.json)中添加 'onReachBottomDistance': 50 选项来设置触底距离。具体实现方式可以参考以下代码:
{
"navigationBarTitleText": "首页",
"onReachBottomDistance": 50
}
在页面配置文件中添加 'onReachBottomDistance' 选项,设置触底距离为 50 个 px。这样,在触底时,系统会自动触发 'onReachBottom' 事件。
以上是解决 UniApp Vue3 页面触底事件 'onReachBottom' 报错的两种方法,开发者可以根据自己的需求选择适合自己的方法。
原文地址: https://www.cveoy.top/t/topic/nzJH 著作权归作者所有。请勿转载和采集!