본문 바로가기

study/Vue.js

Vue - Vuex(state, mutations, action)

Vuex에는 state, mutations, action, getters 등이 있다. 이에대해 공부한 내용을 적어보려고 한다.

 

1. state

- Vuex에서 state는 데이터를 저장시키는 역할을 한다.

- 데이터를 state안에 선언하여 저장할 수 있지만, mutation, action등을 통하여 state에 저장시킬 수 도 있다.

 

2. state안에 데이터 선언

export default {
  // 네임스페이스 트루를 넣어야함
  namespaced: true,

  // 데이터가 들어가는곳
  state: {
    // 회원가입시 저장할 데이터
    signUpData: {
      // 회원가입시 선택한 회원 유형
      selectType : "개인회원"
    },
  },
}

 

3. mutations를 통한 state에 데이터 선언

- mutations src

export default {
  // 네임스페이스 트루를 넣어야함
  namespaced: true,

  // 데이터가 들어가는곳
  state: {
    // 회원가입시 저장할 데이터
    signUpData: {
      // 회원가입시 선택한 회원 유형
      selectType : ""
    },
  },
  // action이 데이터를 바꿔달라고 요청하면 데이터를 바꿔줌
  // state값 변경할 때 사용
  mutations: {
  	// mutations 함수
    ADD_SELECTTYPE(state, value){
      //state에 접근
      state.signUpData.selectType = value
    },
  },
  // 함수가 들어가는 곳
  // DB쓸 때 사용
  // 비동기적 처리를 하고 state의 데이터를 변경할 때 사용한다.
}

- mutations 호출 src

mutations를 호출할 때에는 commit명령을 통해 호출한다.

// vue 파일의 methods
methods: {
    callMutations () {
      // Vuex에 mutations 를 사용할 때 사용
      // Vuex mutations 사용할 때 commit 사용
      // Vuex State에 회원가입시 선택한 회원유형 데이터 저장
      // 파라미터(Vuex파일명/mutations함수명, 보낼데이터)
      this.$store.commit('SignUp/ADD_SELECTTYPE', this.getSelectedData);
      // console.log("데이터 저장 성공")
    },
  },

 

4. action을 통한 state에 데이터 선언

- vue파일에서 action을 호출 -> action은 commit을 통하여 mutations 호출 -> mutations는 state에 데이터 저장과 같은 흐름으로 진행된다.

import { axiosCommon } from '@/api/Index.js'

export default {
    namespaced: true,
    state: {
      users: [],
    },

    mutations: {
      // User 관련
      // action에서 받은 명령 받아옴
      // action에서 받아온 데이터를 state에 저장
      setUser(state, users) {
        state.users = users;
      }
    },

    actions: {
      // user 관련
      async setUsers({ commit }) {
        try {
          const url = 'users';
          const method = 'get';
          // axios를 호출하는 함수를 변수에 담음
          const response = await axiosCommon(url, method);

          if(response.status === 200) {
          	// mutation 호출(commit명령으로 호출한다.)
            // 파라미터 => (mutation 함수명, 보낼 데이터)
            commit('setUser', response.data);
          }
        }
        catch (e) {
          console.log(e)
        }
      },
    }
}

- action 호출 dispatch명령 사용

methods: {
    // test sorce
    callAction() {
      // dispatch명령을 통해서 Vuex action 호출
      // 파라미터 => (Vuex 파일명, action 함수명)
      this.$store.dispatch('SampleUsers/setUsers')
    },
  }

 

5. state에 저장한 데이터 vue파일로 가져오기

- vue파일에서 state에 있는 데이터를 가져오기 위해서는 computed() 를 사용해야한다.

computed: {
    users() {
      // store -> SampleUsers파일 -> state -> users 데이터를 가져와 users()에 저장한다.
      return this.$store.state.SampleUsers.users;
    },
  },