[Vuejs]-How to show a component in Vue.js when an API condition has been met?

0👍

Before accessing the property of the object you can make sure that it has been fetched by adding an additional check as follows:

 <CloudsAnimation v-if="weather && weather.weather[0].main=='Clouds'">
        </CloudsAnimation>

and in data declare it as null first

data () {
    return {
      api_key: '08f1525958fbc6584f628b6dac25a906',
      url_base: 'https://api.openweathermap.org/data/2.5/',
      query: '',
      weather: null
    }

this checks if it’s null first if it is it doesnt render and if its not null it checks the data.You should put this check on every component or on a wrapping div

0👍

As you understand the issue, no need to explain that. I like to keep template free of long if checks and instead use computed properties. So what I would do is to change the if statements to computed properties when there is a long check for null values, so, for example like:

<CloudsAnimation v-if="computedWeather === 'Clouds'"></CloudsAnimation>

<SunAnimation v-else-if="computedWeather === 'Clear'"></SunAnimation>

and then the computed property:

computedWeather: function() {
  return (this.weather && this.weather.weather && this.weather.weather[0] && this.weather.weather[0].main) || null;
}

As you see that would be a nasty long if check in the template, so I prefer computed.

Leave a comment