useScroll.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { ref, computed, nextTick } from "vue";
  2. export const useScroll = () => {
  3. const scrollRef = ref(null);
  4. const targeScrolltDom = computed(() => scrollRef.value.targetScrollDom);
  5. const scrollToTop = async () => {
  6. await nextTick();
  7. targeScrolltDom.value.scrollTo({
  8. top: 0,
  9. left: 0,
  10. behavior: 'smooth'
  11. });
  12. };
  13. const scrollToBottom = async () => {
  14. await nextTick();
  15. if (scrollRef.value) {
  16. targeScrolltDom.value.scrollTo({
  17. top: targeScrolltDom.value.scrollHeight,
  18. left: 0,
  19. behavior: 'smooth'
  20. });
  21. }
  22. }
  23. const scrollToBottomIfAtBottom = async () => {
  24. await nextTick()
  25. if (scrollRef.value) {
  26. const threshold = 100;
  27. const distanceToBottom = targeScrolltDom.value.scrollHeight - targeScrolltDom.value.scrollTop - targeScrolltDom.value.clientHeight;
  28. if (distanceToBottom <= threshold) {
  29. targeScrolltDom.value.scrollTop = targeScrolltDom.value.scrollHeight;
  30. }
  31. }
  32. }
  33. return {
  34. scrollRef,
  35. scrollToTop,
  36. scrollToBottom,
  37. scrollToBottomIfAtBottom
  38. }
  39. }