如何在安装生命周期方法之前使用vue.js?
我正在尝试在vue js中构建一个天气应用程序,当windows加载时,我会得到lat和long,并且运行良好。我定义了两个变量lat和long。我已经将这些变量设置为从javascript navigator对象获得的实际lat和long。 但是,当我试图将这些值传递给真实的天气api时,它不起作用。 下面我有一些代码片段 App.vue如何在安装生命周期方法之前使用vue.js?,vue.js,Vue.js,我正在尝试在vue js中构建一个天气应用程序,当windows加载时,我会得到lat和long,并且运行良好。我定义了两个变量lat和long。我已经将这些变量设置为从javascript navigator对象获得的实际lat和long。 但是,当我试图将这些值传递给真实的天气api时,它不起作用。 下面我有一些代码片段 App.vue 您的函数getLocation可能是一个异步函数,在这种情况下,您需要执行以下操作: 您需要在同一个生命周期钩子中使用两个方法,以便能够告诉一个方法等待另一
您的函数
getLocation
可能是一个异步函数,在这种情况下,您需要执行以下操作:
您需要在同一个生命周期钩子中使用两个方法,以便能够告诉一个方法等待另一个方法。(理论上,这可以在任何生命周期方法中使用)尝试通过控制台记录第一个函数返回的内容。
<template>
<div id="app">
<p>{{ lat }},{{ long }}</p>
<pre> {{ forecast }} </pre>
<Search></Search>
<Main></Main>
<ExtraData></ExtraData>
</div>
</template>
<script>
import Search from "./components/Search.vue";
import Main from "./components/Main.vue";
import ExtraData from "./components/ExtraData";
import WeatherService from "./WeatherService";
export default {
name: "app",
components: {
Search,
Main,
ExtraData
},
data() {
return {
lat: "",
long: "",
forecast: "",
test: "",
city: ""
};
},
methods: {
getLocation: function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(pos => {
this.lat = pos.coords.latitude;
this.long = pos.coords.longitude;
});
}
}
},
beforeMount() {
this.getLocation();
},
mounted() {
WeatherService.getCurrentData(this.lat, this.long).then(data => {
this.forecast = data;
});
}
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
width: 70%;
margin: auto;
padding: 1rem;
}
</style>
const apiKey2 = "f02444d5bb635b838a99faefef6eca70";
const api2 = `http://api.weatherstack.com/current?access_key=${apiKey2}&query=`;
//getting current weather data from lat,long
const getCurrentData = async (lat, long) => {
const response = await fetch(api2 + `${lat},${long}`);
const currentLocationData = await response.json();
return currentLocationData;
};
export default { getCurrentData };
async created(){
await this.getLocation();
WeatherService.getCurrentData(this.lat, this.long).then(data => {
this.forecast = data;
});