개발 언어/NodeJS

Vuex 란 무엇인가

성소아 2022. 9. 6. 17:05

Vuex 란 Vue.js 애플리케이션에 대한 상태 관리 패턴 + 라이브러리 입니다. 

애플리케이션의 모든 컴포넌트에 대한 중앙 집중식 저장소 역할을 합니다.

 

State 

 

Vuex 는 단일 상태 트리를 사용합니다.

즉, 이 객체는 모든 애플리케이션 수준의 상태를 포함하여 '원본 소스' 역할을 합니다.

이는 각 애플리케이션마다 하나의 저장소만 갖게 된다는 것을 의미합니다.

Getters 

둘 이상의 컴포넌트가 이를 사용해야하는 경우 함수를 복제하거나 공유된 헬퍼를 추출하여 여러 위치에서 가져와야 합니다.

 

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

getters 는 store.getters 객체에 노출되고 속성으로 접근 할 수 있습니다.

 

Mutations

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 상태 변이
      state.count++
    }
  }
})

실제로 상태를 변경하는 유일하는 방법은 변이하는 것입니다.

 

Payload 를 가진 Commit 

mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

객체 스타일 Commit 

store.commit({
  type: 'increment',
  amount: 10
})

 

Actions

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    },
    incrementAsync ({ commit }) {
        setTimeout(() => {
          commit('increment')
        }, 1000)
    },
    actionB ({ dispatch, commit }) {
        return dispatch('actionA').then(() => {
          commit('someOtherMutation')
    }),
     async actionA ({ commit }) {
    	commit('gotData', await getData())
      },
      async actionB ({ dispatch, commit }) {
        await dispatch('actionA') // actionA가 끝나기를 기다립니다.
        commit('gotOtherData', await getOtherData())
      }
  }
})

Dispatch는 비동기 액션이면 store.dispatch 가 다른 모듈에서 여러 액션 핸들러를 트리거 하는 것이 가능합니다.

이 경우 반환 된 값은 모든 트리거 된 처리기가 완료되었을 때 처리되는 Promise 입니다.

 


출처 

https://v3.vuex.vuejs.org/kr/


아직 수정중입니다...