uni-app Vite+Vue3抖音小程序hooks使用onPageScroll的问题
uni-app Vite+Vue3抖音小程序hooks使用onPageScroll的问题
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | Windows 10 | CLI |
专业版 22H2 | ||
3.0.0-3081220230817001 |
产品分类:uniapp/小程序/字节跳动
示例代码:
<template>
<view style="height: 120vh;background-color: pink;" >超长内容可滚动</view>
</template>
<script setup lang="ts">
import { onPageScroll } from '[@dcloudio](/user/dcloudio)/uni-app';
import useScrollHook from '@/hooks/useScrollHook'
const {} = useScrollHook();
// 此处注释时, hooks中写的onPageScroll内的回调逻辑不会执行
// onPageScroll(() => {});
</script>
import { onPageScroll } from '[@dcloudio](/user/dcloudio)/uni-app';
export default function useScrollHook () {
// 此处逻辑唯有该Hooks所被调用的页面有执行了onPageScroll才会执行
onPageScroll(() => {
console.log("Hello World");
});
return {};
}
2 回复
有解决吗, 快手也是这个问题, 要页面里面调用onPageScroll,hook里面的才会执行,真的是一堆bug啊
在 uni-app
中使用 Vite
和 Vue3
开发抖音小程序时,onPageScroll
是一个常用的生命周期钩子,用于监听页面的滚动事件。然而,由于抖音小程序的运行环境和 uni-app
的框架限制,使用 onPageScroll
时可能会遇到一些问题。以下是一些常见的注意事项和解决方案:
1. onPageScroll
的基本使用
在 Vue3
中,你可以使用 onMounted
和 onUnmounted
来监听和移除 onPageScroll
事件。
import { onMounted, onUnmounted } from 'vue';
onMounted(() => {
uni.onPageScroll((res) => {
console.log('页面滚动距离', res.scrollTop);
});
});
onUnmounted(() => {
uni.offPageScroll(); // 移除监听
});
2. onPageScroll
在抖音小程序中的限制
抖音小程序的 onPageScroll
事件有一些限制:
- 触发频率:
onPageScroll
的触发频率可能不如预期的高,尤其是在快速滚动时。 - 兼容性:某些版本的抖音小程序可能对
onPageScroll
的支持不完全,导致事件无法正常触发。
3. 解决方案
3.1 使用 usePageScroll
自定义 Hook
你可以封装一个自定义 Hook 来统一处理 onPageScroll
的逻辑,并在抖音小程序中进行兼容性处理。
import { onMounted, onUnmounted, ref } from 'vue';
export function usePageScroll() {
const scrollTop = ref(0);
const handlePageScroll = (res) => {
scrollTop.value = res.scrollTop;
};
onMounted(() => {
uni.onPageScroll(handlePageScroll);
});
onUnmounted(() => {
uni.offPageScroll(handlePageScroll);
});
return { scrollTop };
}
在组件中使用:
import { usePageScroll } from '@/hooks/usePageScroll';
export default {
setup() {
const { scrollTop } = usePageScroll();
return {
scrollTop,
};
},
};
3.2 手动监听滚动事件
如果 onPageScroll
无法满足需求,可以考虑手动监听滚动事件。例如,使用 scroll-view
组件替代页面的默认滚动,并通过 scroll
事件来监听滚动。
<template>
<scroll-view scroll-y [@scroll](/user/scroll)="handleScroll">
<!-- 页面内容 -->
</scroll-view>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const scrollTop = ref(0);
const handleScroll = (event) => {
scrollTop.value = event.detail.scrollTop;
};
return {
scrollTop,
handleScroll,
};
},
};
</script>