Open
Description
// 你的答案
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
// Implement ...
type CallbackType = Parameters<typeof window.addEventListener>;
function useEventListener(
target: EventTarget,
event: string,
callback: CallbackType[1]
) {
onMounted(() => target.addEventListener(event, callback));
onUnmounted(() => target.removeEventListener(event, callback));
}
// Implement ...
function useMouse($el: object = window) {
const x = ref(0);
const y = ref(0);
useEventListener($el, 'mousemove', (e: MouseEvent) => {
x.value = e.clientX;
y.value = e.clientY;
});
return { x, y };
}
const { x, y } = useMouse();
</script>
<template>Mouse position is at: {{ x }}, {{ y }}</template>