webfansplz / vuejs-challenges

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

25 - useMouse #2699

Open LauGM opened 3 months ago

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

// Implement ...
function useEventListener(target, event, callback) {
  onMounted(()=>target.addEventListener(event, callback));
  onUnmounted(()=>target.removeEventListener(event, callback));
}

// Implement ...
function useMouse() {
    const x= ref(0); 
    const y= ref(0); 
  useEventListener(window, "mousemove", (event) => {
    x.value=event.pageX;
    y.value=event.pageY;
  })

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

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