【前端工具类】003-实时获取鼠标位置的工具类:useMousePosition
文章目录
- 【前端工具类】003-实时获取鼠标位置的工具类:useMousePosition
- 一、Vue3 usexxx 写法
- 1、代码
- 2、使用示例
一、Vue3 usexxx 写法
1、代码
import { ref, onMounted, onUnmounted } from "vue";
export function useMousePosition() {
const x = ref(0);
const y = ref(0);
function handleMouseMove(event: MouseEvent) {
x.value = event.clientX;
y.value = event.clientY;
}
onMounted(() => {
document.addEventListener("mousemove", handleMouseMove);
});
onUnmounted(() => {
document.removeEventListener("mousemove", handleMouseMove);
});
return { x, y };
}
2、使用示例
<template>
<div>
<p>鼠标当前位置:({{ position.x }}, {{ position.y }})</p>
</div>
</template>
<script>
import { useMousePosition } from "@/hooks/useMousePosition";
export default {
setup() {
const position = useMousePosition();
return { position };
},
};
</script>