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

相关推荐
GIS之路2 小时前
GDAL 实现影像裁剪
前端·python·arcgis·信息可视化
AGMTI2 小时前
webSock动态注册消息回调函数功能实现
开发语言·前端·javascript
码界奇点2 小时前
基于SpringBoot+Vue的前后端分离外卖点单系统设计与实现
vue.js·spring boot·后端·spring·毕业设计·源代码管理
不会Android的潘潘2 小时前
受限系统环境下的 WebView 能力演进:车载平台 Web 渲染异常的根因分析与优化实践
android·java·前端·aosp
建军啊2 小时前
java web常见lou洞
android·java·前端
阳无2 小时前
宝塔部署的前后端项目从IP访问改成自定义域名访问
java·前端·部署
Galloping-Vijay2 小时前
解决 WSL2 + Windows Hosts + 开启 VPN 后无法访问本地 Web 服务的问题
前端·windows
不吃香菜的猪2 小时前
使用@vue-office/pdf时,pdf展示不全
javascript·vue.js·pdf
wuhen_n2 小时前
TypeScript的对象类型:interface vs type
前端·javascript·typescript
见路不走!2 小时前
后端返回Blob文件流,前端实现导出
前端