You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:50:26