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

相关推荐
Jmyd01235 小时前
Web端3D营销展厅技术实现路径:从素材上云到线索回流的数据链路
前端·3d·性能优化·三维数字化
半个落月5 小时前
LangChain Agent 中间件实战(上):生命周期、状态、短路与工具包
javascript·langchain
砚凝霜5 小时前
【软考信息安全】第二十二章 Web服务器安全分析与增强——Apache与IIS
服务器·前端·安全
半个落月5 小时前
LangChain Agent 中间件实战(下):DeepAgents文件权限、长期记忆与对话摘要
javascript·langchain
u0111026757 小时前
JPG、PNG、WebP 怎么选?按透明度、体积和使用场景做判断
前端·javascript·vue.js·图像处理·ai作画
jerrywus7 小时前
让 AI 写完代码后交一份报告:我改造了 answer-me-with-html
前端·claude·cursor
派小心.8 小时前
小程序分享链路中来源参数的传递校验
大数据·前端·数据库·人工智能·小程序·数据分析
hhb_6188 小时前
一键生成数据看板,ECharts实战演示
前端·javascript·echarts
Java后端的Ai之路8 小时前
08_React组件API
前端·react.js·前端框架
小马不起床8 小时前
零基础玩转 FastAPI_09:前端基础工程构建
前端·状态模式·fastapi