webfansplz / vuejs-challenges

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

25 - useMouse #2801

Open kai-phan opened 1 month ago

kai-phan commented 1 month ago
<script setup lang="ts">

import { reactive } from 'vue';
import { toRefs } from 'vue';
import { onUnmounted } from 'vue';
import { onMounted } from 'vue';

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

  onUnmounted(() => {
    target.removeEventListener(event, callback);
  })
}

// Implement ...
function useMouse() {
  const position = reactive({ x: 0, y: 0 })

  useEventListener(window, "mousemove", (e) => {
    position.x = e.clientX;
    position.y = e.clientY;
  });

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

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