vue.js - vuejs没有从箭头函数设置数据属性
问题描述
我在这里发生了一件奇怪的事情:
我在 vue 中有这个数据属性
data() {
return {
currentLat: 'intial Lat',
currentLong: 'intial Long',
};
},
mounted() {
this.getCurrentLocation();
},
methods: {
getCurrentLocation() {
navigator.geolocation.getCurrentPosition((position) => {
this.currentLat = position.coords.latitude;
this.currentLong = position.coords.longitude;.
console.log(this.currentLat); this prints 41.2111
});
console.log(this.currentLat); this prints 'intial Lat'
},
},
this.currentLat 未在挂载中设置
我不明白这里发生了什么!太奇怪了!
解决方案
下面是一个转换为 Promise 并使用 async/await 的示例:
async getCurrentLocation() {
const position = await new Promise(resolve => {
navigator.geolocation.getCurrentPosition(position => resolve(position))
});
this.currentLat = position.coords.latitude;
this.currentLong = position.coords.longitude;
console.log(this.currentLat); // shouldn't print initial value
},
推荐阅读
- python - 如何将美丽的汤 find_all() 方法限制为只有一定数量的结果?
- python - 尝试使用 pip 安装 pylivetrader 时出错
- r - R (1) 中具有指定平均值、sd、(2) 在指定范围内的随机数
- angular - 在 jasmine 的 Promise 中测试 http 调用
- gis - geotools 大地测量计算器
- docker - 如何在生产中运行 BERT?
- java - SpringBoot 应用程序需要很长时间才能以调试模式启动
- python - 3d卷积核的权重可视化
- node.js - ReactJS + Axios + NodeJS - _id:无法读取 null 的属性“ownerDocument”
- javascript - 创建具有不同文本的多个页面以使用 javascript 打印