TimeSocks's avatar

Variables not rendering in Vue template

I am building a weather station app, and am trying to add forecast data from the OpenWeather API. I can successfully pull down the data and log it to the console, but for some reason I can't display it in the template.

I am grabbing the next five hours of data and storing it in arrays. At the moment I am just trying to display the first hour. Here's my code:

<template>
  <section>
    <h1>Forecast</h1>

        <i :class="['owf owf-',iconCode[0]]"></i>
        <p>Temperature {{ currentTemp[0] }}</p>

    </div>
  </section>
</template>

<script>
  export default {
      data: function(){
        return {
          time: [],
          currentTemp: [],
          tempMin: [],
          desc: [],
          iconCode: [],
        }
      },

      methods: {
          getWeather() {
            var apiKey = "<apikey>";
            var location = "<location>";
            var units = "metric";
            var url = "http://api.openweathermap.org/data/2.5/forecast?id=" + location + "&APPID=" + apiKey + "&units=" + units;
            this.$http.get(url).then(response => {
              console.log(response.data.list);
              for(var i = 0; i < 5; i++){
                this.time[i] = response.data.list[i].dt_txt;
                this.currentTemp[i] = response.data.list[i].main.temp;
                this.tempMin[i] = response.data.list[i].main.temp_min;
                this.desc[i] = response.data.list[i].weather[0].description;
                this.iconCode[i] = response.data.list[i].weather[0].icon;
              }
            });
          },
      },

      beforeMount(){
        this.getWeather();
      },
  }
</script>

The <h1> and <p> text is rendered but not the data from Vue. What am I doing wrong?

0 likes
2 replies
realrandyallen's avatar

Do you have vue dev tools installed to see if currentTemp is actually getting filled with data from your response to the api?

TimeSocks's avatar
TimeSocks
OP
Best Answer
Level 4

@REALRANDYALLEN - Yes, and yes, they're all populated appropriately.

When I use VDT to inspect the DOM, it shows nothing where the variables should be. I've tried prefacing the {{ }} with an @ to avoid issues with Blade, but it just renders the @.

EDIT: if I use

<p v-if="currentTemp[0]">Temperature {{ currentTemp[0] }}</p>

the p tag doesn't render at all...

EDIT: got it!

You can't set arrays with the likes of:

array[i] = value

Instead you need to use:

array.push(value)

https://vuejs.org/v2/guide/reactivity.html

Please or to participate in this conversation.