无法正确访问 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实例。

相关推荐
恋猫de小郭4 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅10 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606111 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了11 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅11 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅12 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅12 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment12 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅12 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊12 小时前
jwt介绍
前端