Browse Source

添加 offScroll 方法

icssoa 5 months ago
parent
commit
436b06fee1

+ 10 - 0
cool/scroller/index.ts

@@ -18,6 +18,16 @@ class Scroller {
 		cbs.push(callback);
 		cbs.push(callback);
 		this.list.set(path, cbs);
 		this.list.set(path, cbs);
 	}
 	}
+
+	// 取消监听页面滚动
+	off = (callback: (top: number) => void) => {
+		const path = router.path();
+		const cbs = this.list.get(path) ?? [];
+		this.list.set(
+			path,
+			cbs.filter((cb) => cb != callback)
+		);
+	};
 }
 }
 
 
 export const scroller = new Scroller();
 export const scroller = new Scroller();

+ 9 - 5
uni_modules/cool-ui/components/cl-back-top/cl-back-top.uvue

@@ -13,7 +13,7 @@
 
 
 <script setup lang="ts">
 <script setup lang="ts">
 import { getTabBarHeight, hasCustomTabBar, scroller } from "@/cool";
 import { getTabBarHeight, hasCustomTabBar, scroller } from "@/cool";
-import { computed, onMounted, ref, watch, type PropType } from "vue";
+import { computed, onMounted, onUnmounted, ref, watch, type PropType } from "vue";
 import { usePage } from "../../hooks";
 import { usePage } from "../../hooks";
 import { clFooterOffset } from "../cl-footer/offset";
 import { clFooterOffset } from "../cl-footer/offset";
 
 
@@ -33,7 +33,7 @@ const emit = defineEmits(["backTop"]);
 const { screenHeight } = uni.getWindowInfo();
 const { screenHeight } = uni.getWindowInfo();
 
 
 // cl-page 上下文
 // cl-page 上下文
-const { scrollToTop, onScroll } = usePage();
+const { scrollToTop, onScroll, offScroll } = usePage();
 
 
 // 是否显示回到顶部按钮
 // 是否显示回到顶部按钮
 const visible = ref(false);
 const visible = ref(false);
@@ -71,9 +71,7 @@ function toTop() {
 onMounted(() => {
 onMounted(() => {
 	if (isPage.value) {
 	if (isPage.value) {
 		// 监听页面滚动
 		// 监听页面滚动
-		onScroll((top) => {
-			onVisible(top);
-		});
+		onScroll(onVisible);
 	} else {
 	} else {
 		// 监听参数变化
 		// 监听参数变化
 		watch(
 		watch(
@@ -87,6 +85,12 @@ onMounted(() => {
 		);
 		);
 	}
 	}
 });
 });
+
+onUnmounted(() => {
+	if (isPage.value) {
+		offScroll(onVisible);
+	}
+});
 </script>
 </script>
 
 
 <style lang="scss" scoped>
 <style lang="scss" scoped>

+ 8 - 0
uni_modules/cool-ui/hooks/page.ts

@@ -45,6 +45,14 @@ class Page {
 	onScroll = (callback: (top: number) => void) => {
 	onScroll = (callback: (top: number) => void) => {
 		scroller.on(callback);
 		scroller.on(callback);
 	};
 	};
+
+	/**
+	 * 取消监听页面滚动
+	 * @param callback 回调函数
+	 */
+	offScroll = (callback: (top: number) => void) => {
+		scroller.off(callback);
+	};
 }
 }
 
 
 export function usePage(): Page {
 export function usePage(): Page {