vuex


https://ryuzuka.github.io/VUE/tutorial/18_vuex.html


Vue.js 어플리케이션에 대한 상태 관리 패턴 + 라이브러리. (  모든 데이터( state ) 통신을 한 곳에서 중앙 집중식으로 관리한다. )

1. 여러 컴포넌트가 하나의 데이터를 공유하고 있을 때

2. 부모 - 자식 컴포넌트 간의 데이터 공유가 아닌 수평적인 컴포넌트 간의 데이터 공유가 필할때


  • 설치

npm install vuex --save       // 설치 ( 또는 vue-cli setting )

import Vuex from 'vuex'    // import

Vue.use( Vuex );                // 모듈 시스템과 함께 사용하려면 Vue.use()를 통해 명시적으로 추가해야 한다.


  • $store ( 상태관리 패턴 )

- state : 컴포넌트 간 공유될 data

- view : 데이터가 표현될 template

- actions : 사용자의 입력에 따라 반응할 methods


  • state

Vuex의 애플리케이션 상태를 보유하고 있는 컨테이너. 저장소의 상태가 변경되면 효율적으로 대응하고 업데이트 한다.

Vue.use( Vuex )로 인해 모든 자식 컴포넌트에 저장소를 주입 할 수 있다. - this.$store 접근 가능

( 컴포넌트의 data 역할 )

const store = Vuex.Store({
state: {
count: 0                                         // state 는 컴포넌트 간에 공유되는 data 속성을 의미한다.
}
})

new Vue({
el: '#vuex',
store: store,                             // 저장소 주입     
computed: {
count () {
return this.$store.state.count                      // computed를 통해 $store의 state 사용
},

}
})


  • getters

각 컴포넌트에서 수행 로직을 호출하고 Vuex에서 state 변경이 이루어지도록 하는 역할을 한다.

( 컴포넌트의 computed 역할 )

const store = new Vuex.Store({
getters: {
getCount: ( state, getters ) => state.count + 1        // state와 getters를 인자로 받는다.
}
})

new Vue({
computed: {
increasedCount () {
return this.$store.getters.getCount
},
}
})


  • mapGetters

getters의 저장된 속성을 mapGetters를 활용하여 간편하게 사용할 수 있으며 vuex 에서 관리 된다.

import { mapGetters } from 'vuex'

new Vue({

computed: {
// 컴포넌트 자체의 coupute에 정의된 속성과 함께 사용하기 위해 ES6문법 ...을 사용한다.
...mapGetters( ['getCount'] ), // getters의 옵션을 배열로 선언하여 간단하게 사용
...mapGetters({ // getters의 옵션을 객체로 선언하여 직관적으로 사용
mapGetCount: 'getCount'
})
}
})


  • mutations

vuex의 state 값을 변경하는 로직 ( mutations가 낯설다면 기억하기 쉽게 setters로 이해할 수 있다. )

1. 동기 처리 로직 정의 ( actions - 비동기 처리 로직 정의 )

2. commit을 이용하여 state를 변경한다. ( 컴포넌트에서 직접 state에 접근하여 변경 - anti 패턴 )

const store = new Vuex.Store({
mutations: {
setCount: ( state, payload ) => state.count += 1 // 데이터 인자 명은 보통 payload 를 많이 쓴다.
}
})

new Vue({
methods: {
increaseCount () {
this.$store.commit( 'setCount', {} )
}
}
})


  • mapMutations

mapGetters 와 마찬가지로, Vuex 에 내장된 mapMutations 를 이용하여 코드 가독성을 높일 수 있다.

import { mapMutations } from 'vuex'

new Vue({
methods: {
// 컴포넌트 자체의 methods에 정의된 속성과 함께 사용하기 위해 ES6문법 ...을 사용한다.
...Vuex.mapMutations( ['setCount'] ), // getters의 옵션을 배열로 선언하여 간단하게 사용
...Vuex.mapMutations({ // getters의 옵션을 객체로 선언하여 직관적으로 사용
mapSetCount: 'setCount'
})
}
})


  • actions

actions는 비 순차적 또는 비동기 처리 로직들을 선언한다. state의 변경을 추적하기 위해 결국 mutations의 method를 commit하는 구조가 된다.

1. 동기 처리 로직 정의 ( mutations - 동기 처리 로직 정의 )

2. payload, object 스타일의 dispatch를 지원한다.

const store = new Vuex.Store({
actions: {
increase ( context ) {                                  // actions == commit ==> mutations
context.commit( 'setCount', { amount: 10 } ) // payload style

context.commit({ // object style
type: 'setCount',
amount: 10
})
}
}
})

new Vue({
methods: {
increaseCount () {
this.$store.dispatch( 'increase' )
}
}
})


  • mapActions

mapGetters, mapMutations 헬퍼 함수들과 마찬가지로 mapActions 도 동일한 방식으로 사용할 수 있다.

import { mapActions } from 'vuex'

new Vue({
methods: {
// 컴포넌트 자체의 methods에 정의된 속성과 함께 사용하기 위해 ES6문법 ...을 사용한다.
...Vuex.mapActions( ['increase'] ), // getters의 옵션을 배열로 선언하여 간단하게 사용
...Vuex.mapActions({ // getters의 옵션을 객체로 선언하여 직관적으로 사용
mapSetCount: 'increase'
})
}
})


'Vue' 카테고리의 다른 글

es6-promise  (0) 2023.05.19
watch  (0) 2023.04.11
vue-router  (0) 2019.02.23
axios  (0) 2019.02.23
트랜지션  (0) 2019.02.10