如何使用vue.js beforeMount生命周期方法?

时间:2019-12-03 10:35:39

标签: vue.js

我正在尝试在vue js中构建一个天气应用程序,为此,当Windows加载时,我会变得越来越久,并且运行正常。我定义了两个变量lat和long。我已经将这些变量设置为实际纬度,并且很长一段时间我就从javascript导航器对象获取了。 但是,当我尝试将这些值传递给真实的天气api时,它将无法正常工作。 我下面有一些代码片段

  

App.vue

<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>
  

WeatherService.js

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 };

1 个答案:

答案 0 :(得分:0)

您的函数getLocation可能是异步函数,在这种情况下,您需要执行以下操作:

async created(){
  await this.getLocation();
  WeatherService.getCurrentData(this.lat, this.long).then(data => {
      this.forecast = data;
    });

您希望在同一个生命周期挂钩中使用2个方法,以便能够告诉一个在另一个上等待。 (理论上讲,它可以在任何生命周期方法中使用)