【发布时间】:2020-11-27 21:09:34
【问题描述】:
我在这里遇到了一件奇怪的事情:
我在 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 未在挂载中设置
我不明白这里发生了什么!太奇怪了!
【问题讨论】:
-
你用
this.currentLat = position.coords.latitude;改变了它的值 -
是的,但是当我控制台记录它的值时,它给了我初始值而不是位置纬度
-
因为它是异步的,所以你应该在回调中使用它,或者将它转换为promise并使用async/await
-
假设用户屏蔽了他们的地理位置,浏览器会弹出询问权限,回调只有在用户允许他们的地理位置后才会运行