【问题标题】:How to fetch data from API to a dynamic API URL before page loads (empty value problem)如何在页面加载前从 API 获取数据到动态 API URL(空值问题)
【发布时间】:2021-06-13 03:03:28
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript vue.js graphql nuxt.js apollo


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多