useScroll.js 914 B

1234567891011121314151617181920212223242526272829303132333435
  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 scrollToBottom = async () => {
  6. await nextTick();
  7. if (scrollRef.value) {
  8. targeScrolltDom.value.scrollTo({
  9. top: targeScrolltDom.value.scrollHeight,
  10. left: 0,
  11. behavior: 'smooth'
  12. });
  13. }
  14. }
  15. const scrollToBottomIfAtBottom = async () => {
  16. await nextTick()
  17. if (scrollRef.value) {
  18. const threshold = 100;
  19. const distanceToBottom = targeScrolltDom.value.scrollHeight - targeScrolltDom.value.scrollTop - targeScrolltDom.value.clientHeight;
  20. if (distanceToBottom <= threshold) {
  21. targeScrolltDom.value.scrollTop = targeScrolltDom.value.scrollHeight;
  22. }
  23. }
  24. }
  25. return {
  26. scrollRef,
  27. scrollToBottom,
  28. scrollToBottomIfAtBottom
  29. }
  30. }