🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
>[success] # 通过点击获取鼠标坐标 ~~~ 1.下面案例用了两种方式一种是ref 定义响应一种是reactive,为了方便其实 在开发时候可以吧这些定义的'useMouseTracker' 方法放到hook文件下统一管理 ~~~ ~~~ <template> <div class="about"> {{x}} --- {{y}} {{x1}} --- {{y1}} </div> </template> <script lang="ts"> import { onMounted, onUnmounted, reactive, ref, toRefs, } from "vue" function useMouseTracker(){ const x = ref(0) const y = ref(0) const updatePosition = (e:MouseEvent) =>{ x.value = e.clientX y.value = e.clientY } // mounted 声明周期注册事件 onMounted(()=>{ document.addEventListener('click',updatePosition) }) onUnmounted(()=>{ document.removeEventListener('click',updatePosition) }) return { x, y } } function useMouseTracker1(){ const point = reactive({ x:0, y:0 }) const updatePosition = (e:MouseEvent) =>{ point.x = e.clientX point.y = e.clientY } // mounted 声明周期注册事件 onMounted(()=>{ document.addEventListener('click',updatePosition) }) onUnmounted(()=>{ document.removeEventListener('click',updatePosition) }) return toRefs(point) } export default { setup(){ const {x,y} = useMouseTracker() const {x:x1,y:y1} = useMouseTracker1() return { x,y,x1,y1 } } } </script> ~~~ * 放到文件中 ![](https://img.kancloud.cn/8e/d6/8ed681efe8d4d6e54cbe911b178fcd8d_987x539.png)