【发布时间】:2021-10-30 18:13:06
【问题描述】:
我正在尝试在执行另一个代码之前先设置我的地理位置数据。事实证明,如果我这样做,它会给我初始数据。有没有办法等待第一个代码执行完毕,数据可用后,我可以执行第一个代码下面的代码?
<template>
<button @click="start">Start</button>
</template>
<script>
import { ref } from "vue";
export default {
data() {
return {
latitude: ref(0),
longitude: ref(0)
};
},
methods: {
start() {
this.getLocation(); // execute this first
console.log(this.latitude, this.longitude); // execute this after the data is updated
},
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
},
showPosition(position) {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
},
};
</script>
【问题讨论】:
-
使用像 await this.getLocation(); 这样的承诺。 getLocation 函数应该返回在设置纬度和经度时解析的新 Promise。
标签: javascript vue.js vuejs2 async-await vuejs3