본문 바로가기
FRONT/VUE

[vue3] vuex란?

by mangttu 2024. 4. 25.

● state사용법

store.js

더보기
import { createStore } from "vuex";

export default createStore({
  state: {
    showToast : false,
    tostMessage : '',
    toastAlertType : '',
    timeout : null
  },
  mutations: {},
  actions: {}
})

 

상태관리 패턴, 라이브러리이다. 

state 사용법은 아래와 같다. 

더보기
    const store = useStore();
    const showToast = computed(() => store.state.showToast);
    const tostMessage = computed(() => store.getters.toastMessageWidthSmile);
    const toastAlertType = computed(() => store.state.toastAlertType);
 
    const triggerToast = (message, type = 'success') => {
      store.dispatch('triggerToast', message, type);
    }  

computed로 감싸줘야 사용이 가능하다.

 

mutations => 

state값을 동기적으로 바꿀 수 있다.

디버깅하기가 쉽다.

 

actions =>

비동기적 작업 가능하다.


mutations  사용법 

state값을 변경할 때 사용한다.

더보기
mutations: {
    UPDATE_TOAST_MESSAGE(state, payload){
      state.tostMessage = payload;
    },
    UPDATE_TOAST_ALERT_TYPE(state, payload){
      state.toastAlertType = payload;
    },
    UPDATE_TOAST_STATUS(state, payload){
      state.showToast = payload;
    }
  },

state는 상태 값(=기본값)이 무엇인지,

payload는 변경값이 무엇인지

 


actions 사용법 

상태값의 동작을 정의할 때 사용한다.

더보기
triggerToast({ commit }, message, type = 'success'){
      commit('UPDATE_TOAST_MESSAGE', message);
      commit('UPDATE_TOAST_ALERT_TYPE', type);
      commit('UPDATE_TOAST_STATUS', true);

      setTimeout(() => {
        commit('UPDATE_TOAST_MESSAGE', '');
        commit('UPDATE_TOAST_ALERT_TYPE', '');
        commit('UPDATE_TOAST_STATUS', false);
      }, 5000); 
    }

context 안에 { commit } 이라는 함수가 정의됨.

{ commit } 은 

('UPDATE_TOAST_MASSAGE', => 라는 mutations 상태를 찾고, message => 라는 값을 변경할 때 사용함.

getters 사용법 

computed와 비슷한 성질

더보기
 getters: { //computed와 비슷한 성질
    toastMessageWidthSmile(state) {
      return state.tostMessage + ' ^_^';
    }
  }

toastMessageWidthSmile 이라는 함수를 만들어서 state.message 의 값에 + 추가로 string 값을 넣는다.

 

 

'FRONT > VUE' 카테고리의 다른 글

[vue3] teleport, slot 사용법  (0) 2024.04.24
[vue3] 라이프사이클 생명주기  (0) 2024.04.24
[vue3] 자바스크립트 객체 복사/비교  (0) 2024.04.24
[vue3] 이벤트 버블링 이란?  (0) 2024.04.24
[vue3] router-view 사용법  (0) 2024.04.23