无法正确访问 Vue 实例的属性

修改前代码(错误部分)

javascript 复制代码
uni.getLocation({
  type: 'gcj02',
  success: function(res) {
    const latitude = res.latitude;
    const longitude = res.longitude;
    const location = [];
    location.push(latitude);
    location.push(longitude);
    this.locationData = location; // 这里的this指向错误
    console.log(this.locationData);
    // ...
  },
  fail: function(err) {
    // ...
  }
});

原因分析

在 findLocation 方法中, uni.getLocation 的 success 回调使用了普通 function ,导致 this 指向错误,无法正确访问 Vue 实例的 locationData 属性。

修改后代码(正确部分)

javascript 复制代码
uni.getLocation({
  type: 'gcj02',
  success: (res) => {
    const latitude = res.latitude;
    const longitude = res.longitude;
    const location = [];
    location.push(latitude);
    location.push(longitude);
    this.locationData = location; // 这里的this正确指向Vue实例
    console.log(this.locationData);
    // ...
  },
  fail: (err) => {
    // ...
  }
});

本bug是典型的JavaScript中 this 指向问题,通过使用箭头函数可以确保回调函数中的 this 正确指向Vue实例。

相关推荐
铁皮饭盒1 小时前
26年bunjs, elysia+pg一把梭, redis都省了
前端·javascript·后端
lichenyang45314 小时前
Docker 学习笔记(一):为什么需要镜像、容器和仓库?
前端
kyriewen14 小时前
别再对着 TypeScript 报错发呆了:我把 10 个最常见的红色波浪线翻译成了人话
前端·javascript·typescript
IT_陈寒14 小时前
SpringBoot自动配置的坑,我的API突然就404了
前端·人工智能·后端
free3515 小时前
从 0 实现一个 Tiny JavaScript VM:项目架构拆解
javascript
暴走的小呆15 小时前
Vue 2 中 Object 的变化侦测:从 getter/setter 到 Dep、Watcher、Observer
vue.js
奇奇怪怪的15 小时前
Embedding 模型 10+ 横向评测
前端
陈广亮15 小时前
Monorepo 从 0 到 1 实操指南 2026 版:pnpm catalogs + Turborepo 2.x + changesets 全链路
前端
子兮曰15 小时前
OpenMontage 深度解剖:你的 AI 编程助手,其实是个视频工作室
前端·后端·ai编程