useScroll.ts 574 B

12345678910111213141516171819202122232425262728
  1. import { ref, onMounted, onUnmounted } from 'vue';
  2. const getScrollY = () => document?.documentElement?.scrollTop || document?.body?.scrollTop;
  3. export const useScroll = () => {
  4. const scrollY = ref(0);
  5. const handleScroll = () => {
  6. scrollY.value = getScrollY();
  7. };
  8. onMounted(() => {
  9. if (process.client) {
  10. scrollY.value = getScrollY();
  11. window.addEventListener('scroll', handleScroll);
  12. }
  13. });
  14. onUnmounted(() => {
  15. if (process.client) {
  16. window.removeEventListener('scroll', handleScroll);
  17. }
  18. });
  19. return {
  20. scrollY
  21. };
  22. }