- Vuex는 Vue.js 애플리케이션 전용 상태 관리 라이브러리로, 복잡한 컴포넌트 구조에서도 중앙 집중식(state-centralized) 방식으로 상태를 관리할 수 있게 해줍니다.
- Vue 2와 함께 자주 사용되며, Vue 3에서는 Pinia로 점차 넘어가는 추세입니다.
- 아래는
Vuex
상태관리 예제에 대한 전체 구성 설명입니다.
✅ 1. Vuex Store 구조
import { createStore } from 'vuex';
export default createStore({
state: {
...
},
mutations: {
...
},
actions: {
...
}
});
createStore()
는 Vuex 4 (Vue 3 전용)에서 store를 생성하는 함수입니다.✅ 2. state: 상태 저장소
state: {
count: 0,
weatherData: {
icon: 'icon',
temp: 0,
text: 'text',
location: 'location',
city: 'Seoul',
}
}
count
: 숫자 카운터 값
weatherData
: 날씨 정보를 저장할 객체로 초기값을 설정해둔 상태
✅ 3. mutations: 상태(state)를 변경하는 함수
Vuex에서 state는 직접 수정할 수 없고, 반드시 mutations을 통해서만 변경해야 합니다.
mutations: {
addCount(state, payload) {
state.count += 1 + payload;
},
updateWeather(state, payload) {
state.weatherData = payload; // 전체 날씨 데이터를 저장
state.weatherData.icon = payload.weather[0].icon;
state.weatherData.temp = payload.main.temp;
state.weatherData.text = payload.weather[0].description;
state.weatherData.location = payload.sys.country;
state.weatherData.city = payload.name;
},
}
addCount
: 카운트를1 + payload
만큼 증가시킵니다.
updateWeather
: 외부 API에서 받아온날씨 데이터
를weatherData
에 반영
✅ 4. actions: 비동기 작업 처리 (예: API 호출)
actions: {
getWeather(context) {
const API_URL = `https://api.openweathermap.org/data/2.5/weather?q=${context.state.weatherData.city}&appid=API_KEY`
fetch(API_URL)
.then(res => res.json())
.then(data => {
context.commit('updateWeather', data);
})
.catch(err => {
alert('에러가 발생했습니다.');
})
}
}
getWeather
는 fetch로 날씨 API 호출하고,
- 받아온 데이터를
context.commit()
으로 mutation에 넘겨서 상태를 변경합니다.
context.commit()은 commit('mutation명', payload)로 해당 mutation을 실행시켜줍니다.
✅ 5. 컴포넌트에서 상태를 사용하는 부분
<template>
<div class="weather-info">
<p>{{ $store.state.weatherData.icon }}</p>
<div class="icon">
<img :src="`https://openweathermap.org/img/wn/${$store.state.weatherData.icon}.png`"
:alt="props.weatherData.icon" />
</div>
<div class="temp">{{ ($store.state.weatherData.temp - 273.15).toFixed(1) }}°C</div>
<div class="text">{{ $store.state.weatherData.text }}</div>
<div class="location">{{ $store.state.weatherData.city }}, {{ $store.state.weatherData.location }}</div>
</div>
</template>
여기서 중요한 점들:
{{ $store.state.weatherData.xxx }}
: Vuex에서 전역 상태를 가져옴
img
의src
는 OpenWeatherMap에서 제공하는 아이콘 주소 형식
- 온도는 켈빈(K)을 섭씨(℃)로 바꾸기 위해
273.15
처리
🔄 흐름 요약 (전체 데이터 흐름도)
[1] 컴포넌트에서 -> $store.dispatch('getWeather')
↓
[2] actions.getWeather() -> fetch()로 날씨 데이터 받아옴
↓
[3] commit('updateWeather', data)
↓
[4] mutations.updateWeather() -> state.weatherData 수정
↓
[5] 컴포넌트는 $store.state.weatherData를 사용하여 자동으로 UI 갱신
Share article