TimeSocks
453
2
Vue

How can I make this code DRYer?

Posted 6 months ago by TimeSocks

I am building a weather station app with the OpenWeather API, Vue, and Laravel. I am grabbing the next 5 hours of forecast data which I want to display in columns. Here's my component:

<template>
  <section>
    <h1>Forecast</h1>
      <div class="columns">
        <div class="column">
          <div class="card">
              <div class="card-content">
                <p class="title has-text-centered">
                  <i :class="['owf owf-2x owf-'+iconCode[0]]"></i>
                </p>
                <p class="subtitle">
                  Temperature {{ currentTemp[0] }}ยบ
                </p>
                <p class="subtitle is-size-6">
                  Min. Temp. {{ tempMin[0] }}
                </p>
                <p class="subtitle">{{ desc[0] }}</p>
                <footer class="card-footer">
                  <p class="card-footer-item">
                    {{ time[0] }}
                  </p>
                </footer>
              </div>
          </div>

        </div>
        <div class="column"></div>
        <div class="column"></div>
        <div class="column"></div>
        <div class="column"></div>
      </div>

    </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 => {
              for(var i = 0; i < 5; i++){
                this.time.push(response.data.list[i].dt_txt.substr(11,5));
                this.currentTemp.push(Math.round(response.data.list[i].main.temp));
                this.tempMin.push(Math.round(response.data.list[i].main.temp_min));
                this.desc.push(response.data.list[i].weather[0].description);
                this.iconCode.push(String(response.data.list[i].weather[0].id).trim());
              }
            });
          },
      },

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

Obviously I could just use the same code in each column with a different index in the arrays each time, but that seems wasteful. I assume I can do something with v-for but I don't know enough about Vue to know how to do it, especially when using multiple arrays in a component. How can I do this?

Please sign in or create an account to participate in this conversation.