728x90
반응형
Vuex가 무엇인지, Vuex를 이용해 Vue 전역 상태 관리하는 방법이 궁금하다면?
2025.11.20 - [Web/Vue] - Vuex 기초: Vue 전역 상태 관리 (state, getters, mutations, actions, modules)
Vuex 기초: Vue 전역 상태 관리 (state, getters, mutations, actions, modules)
Vue에서 컴포넌트끼리 데이터를 주고 받는 방식이 궁금하다면?2025.11.19 - [Web/Vue] - Vue.js SFC, props, emit으로 부모-자식 데이터 흐름 잡기 Vue.js SFC, props, emit으로 부모-자식 데이터 흐름 잡기Vue가 뭔지,
sproutinghye.tistory.com
이번에는 아주 간단한 전역 TODO 리스트 예제를 만들어서
state → getters → mutations → actions 흐름을 한 번에 보겠습니다.
스토어 구현
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
exort default new Vuex.Store({
state: {
todos: [],
loading: false,
error: null
},
getters: {
doneTodos(state) {
return state.todos.filter(t => t.completed)
},
doneCount(state, getters) {
return getters.doneTodos.length
}
},
mutations: {
SET_LOADING(state, flag) {
state.loading = flag
},
SET_ERROR(state, message) {
state.error = message
},
SET_TODOS(state, todos) {
state.todos = todos
},
TOGGLE_TODO(state, id) {
const target = state.todos.find(t => t.id === id)
if (target) target.completed = !target.completed
}
},
actions: {
async fetchTodos({ commit }) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
const res = await axios.get(
'https://jsonplaceholder.typicode.com/todos?_limit=5'
)
commit('SET_TODOS', res.data)
} catch (e) {
commit('SET_ERROR', 'TODO 목록을 불러오지 못했습니다.')
} finally {
commit('SET_LOADING', false)
}
}
}
})
컴포넌트에서 사용하기
<!-- TodoView.vue -->
<template>
<div>
<h2>Vuex TODO 예제</h2>
<button @click="fetchTodos">TODO 불러오기</button>
<p v-if="loading">로딩 중...</p>
<p v-else-if="error">{{ error }}</p>
<ul v-else>
<li
v-for="todo in todos"
:key = "todo.id"
:style = "{ textDecoration: todo.completed ? 'line-through' : 'none' }"
>
<input
type="checkbox"
:checked="todo.completed"
@change="TOGGLE_TODO(todo.id)"
/>
{{ todo.title }}
</li>
</ul>
<p>완료된 항목: {{ doneCount }}개</p>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
computed: {
...mapState(['todos', 'loading', 'error]),
...mapGetters(['doneCount'])
},
methods: {
...mapActions(['fetchTodos'])
...mapMutations(['TOGGLE_TODO'])
}
}
</script>
흐름을 다시 정리해보겠습니다.
- 버튼 클릭 → fetchTodos 액션 디스패치
- 액션 내부에서 API 호출 → 성공 시 SET_TODOS mutation 커밋
- mutation이 state.todos를 변경 → 화면 자동 업데이트
- 체크박스 클릭 → TOGGLE_TODO mutation 커밋 → 완료 상태 토글
- doneCount getter로 완료 개수 계산
728x90
반응형
'Framework > Vue' 카테고리의 다른 글
| Vue CLI로 Vue 프로젝트 만들기 (0) | 2025.11.21 |
|---|---|
| Vuex 모듈(modules)로 스토어 깔끔하게 나누기 (0) | 2025.11.21 |
| Vuex 기초: Vue 전역 상태 관리 (state, getters, mutations, actions, modules) (1) | 2025.11.20 |
| Vue Router와 Axios 활용해 라우팅 + API 연동으로 SPA 만들기 (0) | 2025.11.20 |
| Vue Router 기초 (Vue 2 + Vue Router 3) (1) | 2025.11.19 |