page.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { router, useParent } from "@/cool";
  2. import { computed, watch } from "vue";
  3. type PageScrollCallback = (top: number) => void;
  4. class Page {
  5. listeners: PageScrollCallback[] = [];
  6. pageRef: ClPageComponentPublicInstance | null = null;
  7. constructor() {
  8. this.pageRef = useParent<ClPageComponentPublicInstance>("cl-page");
  9. if (this.pageRef != null) {
  10. // TODO: 小程序异常
  11. watch(
  12. computed(() => this.pageRef!.scrollTop),
  13. (top: number) => {
  14. this.listeners.forEach((listener) => {
  15. listener(top);
  16. });
  17. }
  18. );
  19. }
  20. }
  21. /**
  22. * 获取页面路径
  23. * @returns 页面路径
  24. */
  25. path() {
  26. return router.path();
  27. }
  28. /**
  29. * 获取滚动位置
  30. * @returns 滚动位置
  31. */
  32. getScrollTop(): number {
  33. return this.pageRef!.scrollTop as number;
  34. }
  35. /**
  36. * 滚动到指定位置
  37. * @param top 滚动位置
  38. */
  39. scrollTo(top: number) {
  40. this.pageRef!.scrollTo(top);
  41. }
  42. /**
  43. * 回到顶部
  44. */
  45. scrollToTop() {
  46. this.pageRef!.scrollToTop();
  47. }
  48. /**
  49. * 监听页面滚动
  50. * @param callback 回调函数
  51. */
  52. onPageScroll(callback: PageScrollCallback) {
  53. this.listeners.push(callback);
  54. }
  55. }
  56. export function usePage(): Page {
  57. return new Page();
  58. }