useScroll.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { onPageScroll } from '@dcloudio/uni-app';
  2. export const useScroll = (height?: number) => {
  3. const scrollTop = ref(0);
  4. const isHide = ref(false);
  5. const opacity = computed(() => {
  6. if (height) {
  7. return Math.max(1 - (scrollTop.value / height), 0)
  8. }
  9. return 0;
  10. });
  11. /**
  12. * 滚动到指定位置
  13. * @param selector
  14. * @param offset
  15. */
  16. const scrollTo = async (selector: string, offset: number = 0) => {
  17. const rect2 = await getRect(selector);
  18. uni.pageScrollTo({
  19. scrollTop: scrollTop.value + rect2.top - offset,
  20. duration: 500
  21. });
  22. }
  23. /**
  24. * 获取指定位置的矩形
  25. * @param selector
  26. * @returns
  27. */
  28. const getRect = (selector: string) => {
  29. return new Promise((resolve: (rect: { top: number, height: number }) => void) => {
  30. const query = uni.createSelectorQuery();
  31. query.select(selector).boundingClientRect(function (rect) {
  32. resolve(rect as { top: number, height: number });
  33. }).exec();
  34. });
  35. }
  36. onHide(() => {
  37. isHide.value = true;
  38. })
  39. onShow(() => {
  40. isHide.value = false;
  41. })
  42. onPageScroll((e: any) => {
  43. if (!isHide.value) {
  44. scrollTop.value = e.scrollTop
  45. }
  46. });
  47. return {
  48. scrollTop,
  49. opacity,
  50. scrollTo,
  51. getRect
  52. };
  53. }