[Vuex] vue 데이터 관리

양찌·2022년 7월 10일
0

Vue

목록 보기
3/4

설치

npm i vuex

기본 설정

여러 개의 store 파일 관리

  • 구조

    • src > store > index.js
    • src > store > modules > userStore.js, postStore.js,
  • src > store >index.js

import Vuex from "vuex";
import userStroe from "./modules/userStore"
import postStore from "./modules/postStore"

export default new Vuex.Store({
  modules: {
    userStore,
    postStore 
  }
});
  • src > store > modules > userStore.js
const userStore = {
  namespaced: true,
  state: {
    // 상태 관리하는 곳
  },
  getters: { 
     // 컴포넌트에서 state를 사용할 수 있게 해주는 곳
  },
  mutations: {
    // state 변경하는 곳
  },
  actions: { 
     //비동기 요청, mutations 호출
   }
}

export default userStore;
  • src > main.js
import { createApp } from "vue";
import App from "./App.vue";
import store from "./store/index.js"

createApp(App).use(store).mount('#app')


getters

  • state 호출 방법인 this.$store.state.데이터 의 대안

getters 등록

// userStore.js

const userStore = {
  namespaced: true,
  state: {
    loginUserName : "",
  },
  getters: {
    GE_USER_NAME : state => state.loginUserName
  }
}

mapGetters

  • store의 getters를 가져옴
  • computed에 작성
  • namespace를 사용하기 때문에 키 이름을 적어줌
  • 2가지 방식으로 가져올 수 있음
    1. 이름 지정해서 가져오기
      1. ...mapGetters( 스토어A, { 작명 : ‘getters이름’ } )
    2. getters 이름 그대로 사용해서 가져오기
      1. ...mapGetters( 스토어A, [ ’getters이름’ ] )
// MyPage.vue

<template>
  <div>
    {{  }}
  </div>
</template>
<script>
import { mapGetters } from 'vuex';

const userStore = 'userStore';

export default {
...
data () {
  return {
    userName : ""
  }
},
computed: {

  // 1) 이름 지정해서 가져오기
  ...mapGetters(userStore, {
    storeUserName : 'GE_USER_NAME' // 데이터 바인딩하는 것처럼 사용가능
  });
	
 // 2) getters 이름 그대로 사용해서 가져오기
  ...mapGetters(userStore, [
    'GE_USER_NAME'
  ]);
},
methods : {
  setUserName : function () {
    // 1)
    this.userName =  this.storeUserName;

    // 2)
    this.userName = this.GE_USER_NAME;
  }
}
}
</script>


mutations

  • state 값을 변경하는 로직 (settersA)
  1. 인자를 받아 vuex에 넘겨 줄 수 있고
  2. computed가 아닌 methods에 등록
  • actions와 차이점
  1. mutations는 동기적 로직 정의
  2. actions는 비동기적 로직 정의
  • .commit() 사용

mutations 등록

// userStore.js

const userStore = {
  namespaced: true,
  state: {
    loginUserName : "",
  },
  mutations: {
     MU_USER_NAME : (state , payload) => {
        // payload : .commit을 통해 전달받은 데이터
        state.loginUserName = payload
     }
  }
}

mutations 사용

  • 사용
    • this.$store.commit(’mutations 메소드명’)
    • this.$store.commit(’mutations 메소드명’, 전달데이터)
  • 주의 : store를 모듈화 하였을 경우
    • .commit(“store이름/mutation 메소드명”)
// MyPage.vue
methods: {
  setUserName() {
    this.$store.commit('userStore/MU_USER_NAME', this.userName);
  }
}


actions

  • mutations에는 순차적인 로직들만 선언
  • actions에는 비 순차적 또는 비동기 처리(axios 등) 로직들을 선언
  • dispatch() 사용

actions 등록

// userStore.js

const userStore = {
  namespaced: true,
  state: {
    loginUserName : "",
    followerList : []
  },
  mutations: {
    MU_USER_FOLLOWER_LIST : (state, payload) => {
       state.followerList = payload.followerList;
    }
  },
  actions: {
     AC_USER_FOLLOWER_LIST : (context) => {
        axios
          .get('유저 팔로우 받아오는 url')
          .then(res => {
              return context.commit('MU_USER_FOLLOWER_LIST', 
                                { followerList : res.data }
                                )
           })
          .catch(err => throw(err))

     }
  }
}

actions 사용

  • dispatch() 사용
  • 주의 : store를 모듈화 했을 경우
    • .dispatch(’store명/actions명’)
// MyPage.vue
import { mapActions } from 'vuex';

mounted() {
  this.$store.dispatch('userStore/AC_USER_FOLLOWER_LIST')
}

...

methods: {
  ...mapActions('userStore', ['AC_USER_FOLLOWER_LIST'])
}


다른 store에 있는 getters, mutations,actions 사용

user store에서 contract store에 있는 mutations 사용

상황

userStore에서 로그아웃 actions(다른 스토어 있는 state 값을 초기화)을 만들기

1. mutations 작성

// contractStore.js
// userStore.js 에서 contractStore.js에 있는 상태를 초기화 시키기 위한 mutations 정의

const contractStore = {
  namespaced: true, // 이 값을 true로 해줘야 전역에서 이 store를 contractStore라는 이름으로 사용할 수 있음
  state: {
    contractData: {},
  },
  getters: {
    CONTRACT_DATA: (state) => state.contractData,
  },
  mutations: {
    MU_RESET_STATE(state) {
      state.contractData = {}; // contract store state 초기화
    },
  }
)

export default contractStore;

2. actions 작성

// userStore.js

//... 생략

actions: {
    AC_LOGOUT({ commit }, payload) {
// 이 actions를 사용하는 곳에서 비동기(async/await)로 받고자 return 을 해줌 
      return axios
        .post("/user/logout", { userId: payload.userId })
        .then((res) => {
          if (res.data === "/") {
            commit("MU_RESET_STATE"); // userStore.js(local_현재 작성된 페이지 안) 에 있는 mutation
            // { root: true } 를 입력해줌으로써 다른 store에 있는 mutations 메소드를 사용할 수 있음.
            // 밑에 있는 3개의 mutations는 다른 store에 있는 mutatios이다.
            commit("contractStore/MU_RESET_STATE", payload, { root: true });
            commit("issueStore/MU_RESET_STATE", payload, { root: true });
            commit("mypageStore/MU_RESET_STATE", payload, { root: true });
          }
          return res.data;
        })
        .catch((err) => alert(err));
    },
}

// ... 생략
profile
신입 개발자 입니다! 혹시 제 글에서 수정이 필요하거나, 개선될 부분이 있으면 자유롭게 댓글 달아주세요😊

2개의 댓글

comment-user-thumbnail
2022년 11월 18일

혹시 userStore.js파일에 state영역은 새로고침 시 전부 값이 사라지게 되나요?

1개의 답글