Vue3自定义光标报错:Uncaught TypeError: Cannot read properties of undefined (reading 'x')
问题解决:Vue3自定义光标报错修复
错误原因
你代码里的computed写法完全不符合Vue选项式API的规范,直接在computed对象中写return字段会导致this指向异常,进而无法读取this.x和this.y,触发Cannot read properties of undefined (reading 'x')错误。
修正后的完整代码
<template> <div id="cursor" :style="cursorPoint"></div> </template> <style> #cursor { position: fixed; width: 20px; height: 20px; border-radius: 100%; background-color: white; top: 0; left: 0; z-index: 10000; /* 隐藏系统光标,让自定义光标完全替代 */ pointer-events: none; } </style> <script> export default { data() { return { x: 0, y: 0, } }, methods: { moveCursor(e) { // 光标宽高20px,减去10px让光标中心对齐鼠标位置 this.x = e.clientX - 10; this.y = e.clientY - 10; } }, computed: { // 正确定义计算属性:命名为cursorPoint,返回样式字符串 cursorPoint() { return `transform: translate(${this.x}px, ${this.y}px)`; } }, mounted() { document.addEventListener("mousemove", this.moveCursor); }, // 添加钩子移除事件监听,防止内存泄漏 beforeUnmount() { document.removeEventListener("mousemove", this.moveCursor); } } </script>
关键改动说明
- 修正computed写法:将
computed改为正确的函数形式,命名为cursorPoint(与模板中绑定的cursorPoint对应),通过函数返回样式字符串,此时this能正确指向组件实例,正常访问x和y。 - 调整光标偏移量:原代码中减去15px会导致光标偏移错误,改为减去10px(宽高的一半),让自定义光标中心与鼠标位置对齐。
- 添加事件移除逻辑:在
beforeUnmount钩子中移除mousemove事件监听,避免组件销毁后事件仍然存在导致内存泄漏。 - 新增pointer-events: none:让自定义光标不拦截鼠标事件,避免页面其他元素无法响应鼠标操作。
内容的提问来源于stack exchange,提问作者David Pham
相关产品推荐
相关产品推荐

