Open
Description
// 你的答案
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue";
function useEventListener(target: Window, event: string, callback: any) {
onMounted(() => target.addEventListener(event, callback));
onUnmounted(() => target.removeEventListener(event, callback));
}
function useMouse() {
const x = ref(0);
const y = ref(0);
const handleMouseMove = (e: MouseEvent) => {
x.value = e.clientX;
y.value = e.clientY;
};
useEventListener(window, "mousemove", handleMouseMove);
return { x, y };
}
const { x, y } = useMouse();
</script>
<template>Mouse position is at: {{ x }}, {{ y }}</template>