본문 바로가기
Dev/실습

[Spring Boot + Vue.js] 게시판 만들기 - 날짜, 시간, 날씨

by dev_jsk 2021. 1. 13.
728x90
반응형

이번 포스팅에서는 다양한 곳에서 사용하기 위해 만든 공통 컴포넌트 중 상단바에서 사용되는 날짜, 시간, 날씨 컴포넌트를 알아보자

날짜, 시간 컴포넌트

현재 날짜와 시간을 표시해주는 컴포넌트로 JavaScript의 Date 객체를 이용하여 구현

 

구현

<template>
  <div id="clock">
    <v-icon small>mdi-calendar</v-icon> {{ date }}
    <br />
    <v-icon small>mdi-clock-outline</v-icon> {{ time }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      week: ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'],
      time: '',
      date: '',
    }
  },
  mounted() {
    setInterval(this.updateTime, 1000)	// 1초마다 시간 갱신
  },
  methods: {
    updateTime() {
      var cd = new Date()
      // 날짜 출력
      this.date =
        this.zeroPadding(cd.getFullYear(), 4) +
        '/' +
        this.zeroPadding(cd.getMonth() + 1, 2) +
        '/' +
        this.zeroPadding(cd.getDate(), 2) +
        ' ' +
        this.week[cd.getDay()]
      // 시간 출력
      this.time =
        this.zeroPadding(cd.getHours(), 2) +
        ':' +
        this.zeroPadding(cd.getMinutes(), 2) +
        ':' +
        this.zeroPadding(cd.getSeconds(), 2)
    },
    zeroPadding(num, digit) {
      var zero = ''
      for (var i = 0; i < digit; i++) {
        zero += '0'
      }
      return (zero + num).slice(-digit)
    },
  },
}
</script>

<style scoped>
#clock {
  font-size: 0.875rem;
  font-weight: 500;
}
</style>
  • zeroPadding 함수는 인수로 숫자와 자릿수를 전달하여 해당 자릿수를 만들기 위해 빈 곳에 0을 추가하는 함수이다.

동작 확인

 

날씨 컴포넌트

특정 지역의 날씨정보를 표시하는 기능으로 OpenWeatherMap API를 이용하여 구현

 

구현

<template>
  <div id="weather">
    <!-- 날씨 정보가 있을 경우 -->
    <div v-if="typeof weather.main != 'undefined'">
      <div :title="weather.weather[0].main">
        <!-- Clear -->
        <v-icon v-if="code == 800">{{ icons[5] }}</v-icon>
        <!-- Thunderstorm -->
        <v-icon v-else-if="code.substr(0, 1) == 2">
          {{ icons[0] }}
        </v-icon>
        <!-- Drizzle -->
        <v-icon v-else-if="code.substr(0, 1) == 3">
          {{ icons[1] }}
        </v-icon>
        <!-- Rain -->
        <v-icon v-else-if="code.substr(0, 1) == 5">
          {{ icons[2] }}
        </v-icon>
        <!-- Snow -->
        <v-icon v-else-if="code.substr(0, 1) == 6">
          {{ icons[3] }}
        </v-icon>
        <!-- Atmosphere -->
        <v-icon v-else-if="code.substr(0, 1) == 7">
          {{ icons[4] }}
        </v-icon>
        <!-- Clouds -->
        <v-icon v-else>
          {{ icons[6] }}
        </v-icon>
      </div>
      <div>{{ Math.round(temp) }}℃</div>
    </div>
    <!-- 날씨 정보가 없을 경우 -->
    <div v-else>
      <div>
        <v-icon>mdi-cancel</v-icon>
      </div>
      <div>
        {{ weather.cod }}
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data: function() {
    return {
      api_key: 'YOUR_API_KEY',
      url_base: 'https://api.openweathermap.org/data/2.5/',
      weather: {},
      code: '',
      temp: 0,
      // 날씨 표현 시 사용될 icon 배열
      icons: [
        'mdi-weather-lightning-rainy', // 2xx : Thunderstorm
        'mdi-weather-rainy', // 3xx : Drizzle
        'mdi-weather-pouring', // 5xx : Rain
        'mdi-weather-snowy', // 6xx : Snow
        'mdi-weather-fog', // 7xx : Atmosphere
        'mdi-weather-sunny', // 800 : Clear
        'mdi-weather-cloudy', // 8xx : Clouds
      ],
    }
  },
  mounted() {
    // API 요청 URL (지역 Seoul 고정)
    let fetchUrl = `${this.url_base}weather?q=Seoul&units=metric&APPID=${this.api_key}`
    fetch(fetchUrl)
      .then(response => {
        return response.json()
      })
      .then(result => {
        this.weather = result // 날씨 정보
        this.temp = result.main.temp // 기온
        this.code = result.weather[0].id.toString() // 날씨 코드
      })
  },
}
</script>

<style scoped>
#weather {
  font-size: 0.875rem;
  font-weight: 500;
}
</style>
  • icons 배열의 사용 용도는 특정 날씨 코드에 따라 해당 날씨 아이콘을 표시하기 위함으로 공식 사이트에서 제공하는 날씨 코드표에 따라 맨 앞자리를 통해 해당 아이콘을 표시하도록 구현하였다.
  • API Key는 공식 사이트에서 발급받을 수 있다.
  • API 요청 시 지역을 Text Field를 통해 입력 받아 해당 지역의 날씨 정보를 받아서 표시하도록 구현할 수 있다.

동작 확인

 

728x90
반응형

댓글