如何在页面加载之前从 API 获取数据到动态 API URL空值问题

问题描述

我是 javascript 和 vue 的初学者。我正在使用动态路由,并且试图在页面加载时将数据从我的本地 API(通过 Apollo 的 Graphql)传递到 Openweathermap API URL。问题是 openweather API 返回 400,因为除非我刷新页面,否则 URL 会传递一个空值 (this.city)。在 axios(或 fetch)尝试从 openweather API 获取任何数据之前,我无法弄清楚如何从本地 API 获取值(城市名称)。

简而言之: this.city 作为一个空值传递给 axios URL,它从 API 返回 400 错误,除非我刷新页面(这并不总是工作)。

这是我的代码

<script>
  import venueQuery from '~/apollo/queries/venue/venue'


  export default {
    data() {
      return {
        loading: 0,venues: [],city: '',sunset: '',currentTemp: ''
      }

    },apollo: {
      $loadingKey: 'loading',venues: {
        prefetch: true,query: venueQuery,variables() {
          return {
            slug: this.$route.params.slug
          }
        },result(result) {
          return this.city = result.data.venues[0].temperature

        }
      }
    },created() {

      this.getWeatherInfo()

    },methods: {
      getWeatherInfo() {
        this.$axios
          .$get(`${process.env.WEATHER_BASEAPI}${this.city}${process.env.WEATHER_KEY}`).then(data => {
            this.currentTemp = Math.floor(data.main.temp - 273.15);
            this.sunset = new Date(data.sys.sunset * 1000).toLocaleTimeString("en-GB").slice(0,5)
          })
      }
    }
  }

</script>

任何帮助将不胜感激。

解决方法

由于 city 在组件创建后异步填充,getWeatherInfo()(在 created 钩子中)将在 city 实际设置之前被调用。

您可以在 city 上添加 watcher,这样对数据属性的任何更新都会导致 getWeatherInfo()

export default {
  watch: {
    city() {
      this.getWeatherInfo()
    }
  }
}