uni-app编译到微信小程序不能触发自定义hook中监听的onPageScroll钩子函数

uni-app编译到微信小程序不能触发自定义hook中监听的onPageScroll钩子函数

开发环境 版本号 项目创建方式
Mac 14 CLI

操作步骤:

export const usePageScroll = () => {  
  const scrollTop = ref(0);  

  onPageScroll((e) => {  
    scrollTop.value = e.scrollTop;  
  });  

  return { scrollTop };  
};
<template>  
  <view></view>  
</template>  

<script setup lang="ts">  
import { watchEffect } from 'vue';  
import { usePageScroll } from '@/hooks/useScroll';  

const {scrollTop} = useScroll()  

watchEffect(() => {  
    console.log(scrollTop);  
  });  
</script>

更多关于uni-app编译到微信小程序不能触发自定义hook中监听的onPageScroll钩子函数的实战教程也可以访问 https://www.itying.com/category-93-b0.html

7 回复

参考该issue

更多关于uni-app编译到微信小程序不能触发自定义hook中监听的onPageScroll钩子函数的实战教程也可以访问 https://www.itying.com/category-93-b0.html


好的,了解了。

在const scrollTop = usePageScroll(); 前面加个onPageScroll((e) => {}); 试试

有用的,谢谢解答

改造一下 <template>
<view class="content">
<view class="content" v-for="(item, index) in 50" :key="index">
{{ index }} - {{ item }}
</view>
</view>
</template>

<script setup > import { watchEffect } from 'vue'; import { usePageScroll } from '@/hooks/useScroll'; const scrollTop = usePageScroll(); watchEffect(() => { console.log(scrollTop.value); }); </script>

//hook
import {ref} from “vue”
import {onPageScroll} from ‘@dcloudio/uni-app’
export const usePageScroll = () => {
const scrollTop = ref(0);
onPageScroll((e) => {
scrollTop.value = e.scrollTop;
});
return scrollTop
};

试了,一样还是不行呢

在uni-app中,微信小程序平台对onPageScroll钩子的实现确实存在一些限制。根据你的代码,问题可能出在以下几个方面:

  1. 微信小程序的页面滚动事件需要在页面配置中明确声明:
{
  "enablePullDownRefresh": false,
  "onReachBottomDistance": 50,
  "disableScroll": false  // 必须为false才能触发滚动事件
}
  1. 自定义hook中的onPageScroll在小程序平台可能需要直接绑定到页面实例上。建议改为:
export const usePageScroll = (page: any) => {
  const scrollTop = ref(0);
  
  if(process.env.UNI_PLATFORM === 'mp-weixin') {
    page.onPageScroll = function(e: any) {
      scrollTop.value = e.scrollTop;
    }
  } else {
    onPageScroll((e) => {
      scrollTop.value = e.scrollTop;
    });
  }

  return { scrollTop };
};
  1. 在页面中使用时需要传入当前页面实例:
<script setup>
const pageInstance = getCurrentPages()[0];
const {scrollTop} = usePageScroll(pageInstance);
</script>
回到顶部