프로젝트명 : 날씨 정보 웹사이트
분류 : 웹개발 연습용 토이 프로젝트
사용 툴 :HTML
CSS
JavaScript
Vue.js
(https://openweathermap.org/)에서 API key를 받고 URL Base와 원하는 지역의 명칭을 함께 조합하면
<script>...</script>
<input... @keypress="fetch_weather" .../>
HTML 소스 코드에서 input 태그/요소에 포함되어 있는 @keypress는 키보드에 키가 눌릴 경우에 fetch_weather 함수 불러온다.
fetch_weather(e) {
if (e.key === "Enter") {
fetch(
`${this.url_base}weather?q=${this.query}&units=metic&appid=${this.api_key}`
)
.then((res) => {
return res.json();
})
.then(this.setResults);
}
},
setResults(results) {
this.weather = results;
}
fetch_weather() 함수는 입력된 키가 Enter일 경우,
this.query(입력된 지역의 명칭),
this.url_base(Open Weather의 주소),
this.api_key(나에게 지정된 api key)
를 통해 정보를 가져온다.
정보를 json형태로 바꿔서 돌려주고 setResults()함수에서 결과를 저장한다.
dataBuilder() {
let d = new Date();
let months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
let days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
let day = days[d.getDay()];
let date = d.getDate();
let month = months[d.getMonth()];
let year = d.getFullYear();
return `${day} ${date} ${month} ${year}`;
}
dateBuilder()에서는 Date객체의 메서드를 사용하여 날짜를 구한다.
kelvintoC() {
let temp = Math.round(this.weather.main.temp - 273.15);
return temp;
},
},
};
Open Weather에서 기온 정보를 캘빈으로 주기 때문에 섭씨(Celcius)로 바꿔주기 위해 273.15를 빼준다.
<div
id="app"
:class="
typeof weather.main !== 'undefined'
? kelvintoC() > 5
? 15 < kelvintoC()
? 25 < kelvintoC()
? 'hot'
: 'warm'
: 'cool'
: 'cold'
: ''
"
>
(Conditional Class Binding) 조건에 따라 클래스를 정해주어 해당 기온에 맞는 CSS 스타일을 찾아갈 수 있도록 매칭해준다.
기온이 5도보다 낮으면 'cold' (추운 배경화면)
(기온이 5도보다 높을 때) 기온이 15도보다 낮으면 'cool' (쌀쌀한 배경화면)
(기온이 15도보다 높을 때) 기온이 25도보다 낮으면 'warm' (따뜻한 배경화면)
기온이 25보다 높으면 'hot'(더운 배경화면)
weather.main의 타입이 정의되지 않았을 때 '' (default 배경화면)
etc.
끝.