useKeyboardScroll.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { ref, onMounted, onUnmounted } from 'vue'
  2. export function useKeyboardScroll() {
  3. const scrollPosition = ref(0)
  4. const keyboardHeight = ref(0)
  5. let keyboardShowHandler = null
  6. let keyboardHideHandler = null
  7. // 保存当前滚动位置
  8. const saveScrollPosition = () => {
  9. // 获取当前页面的滚动位置
  10. const pages = getCurrentPages()
  11. if (pages.length > 0) {
  12. scrollPosition.value = pages[pages.length - 1].scrollTop || 0
  13. }
  14. }
  15. // 恢复滚动位置
  16. const restoreScrollPosition = () => {
  17. // 延迟恢复,确保页面布局已更新
  18. setTimeout(() => {
  19. const pages = getCurrentPages()
  20. if (pages.length > 0) {
  21. const page = pages[pages.length - 1]
  22. if (page && typeof page.setData === 'function') {
  23. page.setData({
  24. scrollTop: scrollPosition.value
  25. })
  26. }
  27. }
  28. }, 100)
  29. }
  30. onMounted(() => {
  31. // 监听键盘显示事件
  32. keyboardShowHandler = (e) => {
  33. keyboardHeight.value = e.height
  34. saveScrollPosition()
  35. }
  36. // 监听键盘隐藏事件
  37. keyboardHideHandler = () => {
  38. keyboardHeight.value = 0
  39. restoreScrollPosition()
  40. }
  41. // 绑定事件监听器
  42. uni.onKeyboardHeightChange(keyboardShowHandler)
  43. uni.onKeyboardHeightChange(keyboardHideHandler)
  44. })
  45. onUnmounted(() => {
  46. // 清理事件监听器
  47. if (keyboardShowHandler) {
  48. uni.offKeyboardHeightChange(keyboardShowHandler)
  49. }
  50. if (keyboardHideHandler) {
  51. uni.offKeyboardHeightChange(keyboardHideHandler)
  52. }
  53. })
  54. return {
  55. keyboardHeight,
  56. scrollPosition,
  57. restoreScrollPosition
  58. }
  59. }