webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.69k stars 188 forks source link

25 - useMouse - TS (With proper types + generic) #2702

Open sky0matic opened 3 months ago

sky0matic commented 3 months ago
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

// Implement ...
function useEventListener<E extends Event>(target: EventTarget, event: keyof DocumentEventMap, callback: (event: E) => void) {
  onMounted(() => target.addEventListener(event, callback));
  onUnmounted(() => target.removeEventListener(event, callback));
}

// Implement ...
function useMouse() {
  const x = ref(0);
  const y = ref(0);

  useEventListener<MouseEvent>(window, 'mousemove', event => {
    x.value = event.x;
    y.value = event.y;
  });

  return { x, y };
}
const { x, y } = useMouse()
</script>

<template>Mouse position is at: {{ x }}, {{ y }}</template>