DEV/Vue

Vue / 13강, 14강 / Vuex

Lee_Coder 2022. 7. 17. 22:32
728x90
반응형

 

 

Vue / 12강 / Router, SPA

Vue / 9강 ~ 11강 / Component Life Cycle, Directive Vue / 7강, 8강 / Component의 기본, Data Binding https://ccamanglab.tistory.com/25 Vue / 1~6강 / 프론트엔드 프레임워크와 ES6 프론트엔드 개발자를 위..

ccamanglab.tistory.com

전 강에 이어서 작성하는 글


[State Management]

 

1.상태(State)

 

애플리케이션 데이터

Component 내에서만 유지되고 관리되어야 하는 데이터를 상태라고 표현하지는 않음

어플리케이션 전역에서 이용되는 데이터

그리고 그것을 어떻게 관리할지가 상태관리임

 

2.상태 관리(State Management)

여러 Component로 구성된 애플리케이션에서는 하나의 상태가 하나의 Component에서만 이용되지 않음

애플리케이션 관점에서 상태를 체계적으로 유지 관리해 주어야함

애플리케이션을 상태 중심으로 설계 개발함으로 애플리케이션의 데이터와 데이터의 흐름을 명료하게 할 수 있음

 

3.MVC 구조에서의 데이터 흐름 - Model View Controller

MVC 모델은 기능의 분리가 초점

애플리케이션의 상태를 중심으로 한 흐름이 아님

애플리케이션의 데이터가 양방향으로 이용되어 복잡도가 증가됨

 

4. 상태 관리 패턴의 데이터 흐름

애플리케이션의 데이터는 단방향으로만 이용되어야함

 

[Vuex]

 

1.Vuex

Vue.js를 위한 상태 관리 프레임 워크

 

npm install vuex@next

 

2.One way data flow

Action => State => View => Action (roll and roll)

 

state 애플리케이션에서 관리되어야 하는데이터

view state가 이용되는 component

action state 발생 및 변경을 위한 이벤트

 

3.Vuex의 Flow

mutation : state 변경

 

4.Store Instance

Store Instance(저장소 개념)는 state, actions, mutations로 구성됨

actions과 mutations는 함수로 작성됨

state는 Object Literal임

 

const store = createStore({
	state(){
    return {
    	items: []
    }
    },
    actions : {
    	addItemAction({ commit }, item) {
        	item.id = count++
            commit('addItemMutation', item)
            }
    },
    mutations : {
    	addItemMutation(state, item){
        	state.items.push(item)
            }
		}
     })

 

5.Store Instance 등록

application instance의 use()함수로 application에 등록하여 사용함

app.use(store)

 

6.action 발생

애플리케이션 내에서 Vuex의 구성요소는 this.$store 객체로 접근이 가능함

action은 함수이며 함수 이름을 this.$store.dispatch() 함수에 대입하여 호출함

dispatch 함수를 호출하면서 데이터를 매개변수로 전달할 수 있음

this.$store.dispatch('addItemAction',data)

 

7.state 이용

action 발생에 의해 생성/변경된 state 데이터는 this.$store.state 객체로 획득이 가능함

this.$store.state.items

 


[Vuex의 다양한 활용]

 

1. Module

Store에는 actions, mutations, state가 등록됨

애플리케이션 내에 여러 개 Store 이용 가능

애플리케이션 규모가 크면 상태별로 Store를 여러 개 이용하는 것이 효율적임

Store를 모듈화해서 여러 개 등록하고 구분해서 사용하는 기법

 

2.모듈 선언

하나의 모듈이 하나의 스토어다 라고 인식

모듈은 state, actions, mutations를 가지는 Object Literal임

namespaced : true
모듈을 이름으로 구분해서 사용하겠다는 의미

const countStore = {
namespaced : true,
state(){},
actions:{},
mutations:{}  }

 

3.모듈 등록

Object Literal로 선언된 모듈을 modules 속성으로 등록해서 사용함

const store = createStore({
	modules : {
    countStore : countStore,
    todoStore : todoStore
    }
})

 

4.모듈 이용

Module의 Action 이용

Action 함수 앞에서 모듈명을 추가해 이용함

this.$store.dispatch('countStore/increase')

 

Module의 State 이용

this.$store.state 뒤에 모듈명을 추가해 이용함

this.$store.state.countStore.count

 

5.State

애플리케이션의 상태를 의미함

Object Literal로 선언됨

state(){
	return {
    	count : 0
    }
},

 

6.this.$store로 이용

export default {
computed : {
count() { return this.$store.state.test.count;}
},
};

 

7.mapState 활용

state 값을 쉽게 이용하기 위한 일종의 Helper

mapState에 함수를 등록하면 매개변수로 state를 전달해 줌

import {mapState} from 'vuex'
export default {
computed : mapState({
	myCount : state => state.test.count,
    myCount2 (state) {
    return state.test.count}
}),

> vue로 상태관리를 받는 것은

> component 입장에서 actions을 발생시키고, state 데이터를 가져옴

 

콜 될때 매개변수 객체로 바로 사용할 수 있다는 것이 mapState의 활용 장점이다

 

state값을 직접 mapState를 이용해 획득 가능

...mapState('test',['count']),

 


1.Action

애플리케이션의 State 값 변경을 위해 호출되는 함수

actions : {
	increase({commit}){
    	commit('increase')
        }
},

 

2.Action 함수 호출

this.$store의 dispatch 함수를 이용해 호출함

this.$store.dispatch('test/testAction',100)

 

mapActions함수 이용

Action 함수를 쉽게 이용하기 위한 Helper

...mapActions("test",["testAction"])

 

3.Getter

필수 구성 요소는 아님

Getter는 state를 이용하기 위한 함수

Store에 선언되어 있는 Component 쪽이 아니라 스토어 내에 등록

 

4.Getter 선언

매개 변수로 state가 전달되며 두 번째 매개변수로 다른 Getter를 이용할 수 있는 getters가 전달됨

const getters = {
	doneTodos : state => {
 	   		return state.todos.filter(todo => todo.done)},
    doneTodosCount : (state, getters) => {
        	return getters.doneTodos.length
        }
}

 

5.Getter 이용

mapGetter() 함수로 Getter를 이용함

import { mapState, mapGetters } from 'vuex';
export default {
computed : {
...mapGetters('test',{
doneTodosCount : 'doneTodosCount'
}) },

 

반응형