본문 바로가기
IT/Vue

VueX 사용법 정리

by DOSGamer 2022. 8. 30.
반응형

Vuex란

Vuex 공식사이트

Vuex 는 vue 의 상태관리 라이브러리 입니다

일반적인 vue 에서 상태관리는 State 에 데이터를 저장하고 Actions 으로 State 를 변경합니다

단순한 경우에는 사용이 가능하지만

여러 Vue 가 상태를 공유해야 할 경우 ( 예 ) 로그인 여부, 로그인 아이디 ) 유지보수 하기 어려워집니다

Vuex 는 일반 vue 의 상태관리를 확장해서

Mutations 라는 개념이 추가 되었습니다 (Actions 이 State 를 직접 변경하지 않고 Mutations 을 호출해서 State 를 변경하는 방법)

Mutations 으로 변경하면 Vuex 가 State 를 관리해줍니다

단순한 Vue APP 은 Vuex 를 사용하지 않고 단순한 상태관리나 글로벌 이벤트 버스를 사용하고

중대형 규모의 SPA 로 구축할 경우 Vuex 를 사용하면 좋습니다

State

공통으로 사용하는 변수를 정의

프로젝트 내의 모든 곳에서 참조 및 사용이 가능

// initial state
const state = {
  boards: [],
  posts: []
}

Mutations

state 를 변경하는 역할 (Mutations 를 통해서만 state 를 변경해야 합니다)

동기(Sync) 로 실행됩니다

commit('함수명', '전달인자') 로 실행 시킬 수 있습니다

mutations 선언에서는 state 와 payload 만 사용합니다.

mutations(state, payload) { }

// mutations 실행
commit('SET_USER', user);

// mutations 선언
const mutations = {
  SET_LOGGEDIN: (state, loggedIn) => {
    state.loggedIn = loggedIn;
  },
  SET_USER: (state, user) => {
    state.user = user;
  },
  SET_ACCESSTOKEN: (state, accessToken) => {
    state.accessToken = accessToken;
  }
}

Actions

Mutations 을 실행시키는 역할

Mutations 과 다르게 비동기 (aSync) 로 실행합니다.

dispatch('함수명', '전달인자') 로 실행 시킬 수 있습니다.

비동기 처리이기에 콜백함수로 작성합니다

actions 선언에서는 { rootState, state, dispatch, commit } 과 payload 를 사용합니다

actions( { rootState, state, dispatch, commit }, payload ) { }

rootState : 상위 State 를 접근할 때 사용

state : state 를 접근할 때 사용

dispatch : 다른 actions 를 실행할 때 사용

commit : mutations 를 실행할 때 사용

// actions 실행
dispatch('login', user);

// actions 선언
const actions = {
  login ({ commit }, user) {
    return login(user).then(
      response => {
        const { data } = response;
        commit('SET_LOGGEDIN', true);
        commit('SET_USER', JSON.parse(`{ "id": "${data.id}", "name": "${data.name}" }`));
        commit('SET_ACCESSTOKEN', data.accessToken);
        setAccessToken(data.accessToken);
        setUser(JSON.stringify({ "id": `${data.id}`, "name": `${data.name}` }));
        return Promise.resolve(data);
      },
      error => {
        commit('SET_LOGGEDIN', false);
        const { data } = error.response;
        return Promise.reject(data);
      }
    );
  }
}

// actions 콜백함수로 처리
dispatch('login', user).then( ()=> {  } );

Getters

state 의 정보를 Components 에서 사용

하위 모듈의 getters 를 사용하려면 this.$store.getters["경로명/함수명"]; 를 사용함

// user 모듈의 getAccessToken 함수를 사용하는 방법
config => {
    if (store.getters["user/getAccessToken"]) {
      config.headers.common['Authorization'] = `Bearer ${getAccessToken()}`;
    }
    return config;
}

Components 에서 store 모듈에 접근하는 방법

state 접근

computed 에서 작성

기본접근 - this.$store.state.스테이트명

모듈접근 - this.$store.state.모듈명.스테이트명

...mapState 활용

computed: {
    ...mapState({
      sidebar: state => state.app.sidebar,
      device: state => state.app.device,
      showSettings: state => state.settings.showSettings,
      needTagsView: state => state.settings.tagsView,
      fixedHeader: state => state.settings.fixedHeader
    }),

Mutations 접근

methods 에서 작성

기본접근 - this.$store.commit('함수명')

모듈접근 - this.$store.commit('모듈명/함수명')

...mapMutations 활용

// this.increment() 를 this.$store.commit('increment')에 매핑
// this.decrement() 를 this.$store.commit('decrement')에 매핑
// this.incrementA() 를 this.$store.commit('moduleA/increment')에 매핑
methods: {
    ...mapMutations({
        increment: 'increment',
        decrement: 'decrement',
				incrementA: 'moduleA/increment'
    }),

Actions 접근

methods 에서 작성

기본접근 - this.$store.dispatch('함수명')

모듈접근 - this.$store.dispatch('모듈명/함수명')

...mapActions 활용

// this.increment() 를 this.$store.dispatch('increment')에 매핑
// this.decrement() 를 this.$store.dispatch('decrement')에 매핑
// this.incrementA() 를 this.$store.dispatch('moduleA/increment')에 매핑
methods: {
    ...mapActions({
        increment: 'increment',
        decrement: 'decrement',
				incrementA: 'moduleA/increment'
    }),

Getters 접근

computed 에서 작성

기본접근 - this.$store.getters.함수명

모듈접근 - this.$store.getters["모듈명/함수명"]

...mapGetters 활용

computed: {
    ...mapGetters([
      name: 'user/name',
      avatar: 'avatar',
      roles: 'role/roles'
    ])
  },

상위 모듈의 dispatch, commit 실행 방법

최상위 state 변수를 활용하기 위해서 rootState 를 사용한다

rootState 는 actions 와 gatters 의 인자로만 사용할 수 있다

Mutations 에서 사용하려면 Actions 에서 Mutations 으로 commit 해서 사용한다

dispatch("moduleA/increment", payload, { root: true });


Uploaded by N2T

반응형

'IT > Vue' 카테고리의 다른 글

Vue.js 기본정보 링크  (0) 2022.09.20
Vue Directive & Instance Properties 학습정리  (0) 2022.08.25
Vue Lifecycle 학습정리  (0) 2022.08.25
Vue Event 학습정리  (0) 2022.08.25
Vue Template Syntax 학습정리  (0) 2022.08.25
Vue Component 학습정리  (0) 2022.08.25
Vue Rendering 학습정리  (0) 2022.08.25
Vue Routing 학습정리  (0) 2022.08.25