정보교육/프런트엔드

코딩 자율학습단(Vue.js 프런트엔드 개발 입문) 18일차

@thiskorea 2024. 7. 10. 09:46

11장 날씨 애플리케이션 만들기
11.1 날씨 애플리케이션 살펴보기

날씨 애클리케이션: 홈, 예보, 검색 화면

검색화면에서 조회한 다른 지역의 날씨 데이터를 웹 브라우저 저장소(로컬 스토리지)에 저장
11.2 날씨 애플리케이션 UI 구성하기


11.3 날씨 애플리케이션 기능 구현하기

날씨 api 

https://www.visualcrossing.com/

 

Weather Data & Weather API | Visual Crossing

About Visual Crossing Visual Crossing is a leading provider of weather data and enterprise analysis tools to data scientists, business analysts, professionals, and academics. Founded in 2003, our mission has always been to empower data consumers and analys

www.visualcrossing.com

 

vue/.env 환경파일 설정

VITE_WEATHER_API_KEY=사용자 API KEY
// src/stores/weather.js
import { defineStore } from 'pinia';
import axios from 'axios';
import { ref } from 'vue';

// Base URL for the weather API
const baseURL = 'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline';

// API key from environment variables
const apiKey = import.meta.env.VITE_WEATHER_API_KEY;

// console.log('API Key:', apiKey); // Log the API key to ensure it's correctly loaded

export const useWeatherStore = defineStore('weather', () => {
  // Initial search location
  const address = ref('seoul');
  // Current weather data
  const currentConditions = ref(null);

  // Fetch current weather information
  const getCurrentWeatherInfo = async () => {
    try {
      // Construct the complete URL
      const url = `${baseURL}/${address.value}?unitGroup=metric&key=${apiKey}&contentType=json`;
      const res = await axios.get(url);
      currentConditions.value = res.data.currentConditions;
    } catch (e) {
      console.error(e); // Log error to console
      alert(e.response?.data ? e.response?.data : e.message);
    }
  };

  return { address, currentConditions, getCurrentWeatherInfo };
});
// vue.js.frontend/ch11_weather/vue/src/views/HomeView.vue
<script setup>
import { useWeatherStore } from '@/stores/weather.js';
import { storeToRefs } from 'pinia';
import dayjs from 'dayjs'; // dayjs 라이브러리 로드
import { getImage } from '@/composables/helper.js'; // helper.js 추가
import { onBeforeMount } from 'vue';
const weatherStore = useWeatherStore();
const { currentConditions } = storeToRefs(weatherStore);
onBeforeMount(() => {
  weatherStore.getCurrentWeatherInfo();
});
</script>
<template>
  <header v-if="currentConditions" class="header">
    <!-- 지역 -->
    <h1 class="header__title">
      <span class="material-symbols-outlined"> location_on </span>서울
    </h1>
    <h2 class="header__date">{{ dayjs().format('HH:mm') }}</h2>
  </header>
  <!-- 현재 날씨 -->
  <main v-if="currentConditions" class="main">
    <article class="weather">
      <section class="weather__info">
        <img
          :src="getImage(currentConditions.icon)"
          :alt="`${currentConditions.datetime} ${currentConditions.temp}도`"
          class="weather__img"
        />
        <h3 class="weather_temp">{{ currentConditions.temp }}°</h3>
        <p class="weather_summary">{{ currentConditions.conditions }}</p>

        <ul class="weather__moreList">
          <li class="weather__moreListItem">
            <p class="weather__subtitle">습도</p>
            <p class="weather__desc">{{ currentConditions.humidity }}%</p>
          </li>
          <li class="weather__moreListItem">
            <p class="weather__subtitle">풍속</p>
            <p class="weather__desc">{{ currentConditions.windspeed }}/ms</p>
          </li>
          <li class="weather__moreListItem">
            <p class="weather__subtitle">체감</p>
            <p class="weather__desc">{{ currentConditions.feelslike }}°</p>
          </li>
        </ul>
      </section>
    </article>
  </main>
</template>