[Vuetify] 15. Vuex 기본

Vuex 기본

1. Vuex 구성

State

export const state = () => ({
    account: null,
    isAdmin: null,
    item: null
})

Mutations

export const mutations = {
    currentUser(state, account) {
        state.account = account; // state의 account 변수에 넘겨 받은 account 값을 입력함
    }
}

Actions

export const actions = {
    setAccount({ commit, dispatch }, account) {
        commit('currentUser', account);
        dispatch('setIsAdmin', account.uid);
    }
}

dispatch('setAccount', account);

Components에서 then() 으로 콜백함수 실행

dispatch('setAccount', account)
	.then( () => { } );

export const actions = {
    setAccount({ commit }, account) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                commit('currentUser', account);
                resolve()
            }, 1000)
        })
    }
}

Getters

export const getters = {
    isAuthenticated(state) { // 현재 로그인 상태인지 확인 (true/false)
        return !!state.user;
    },
    
    getAccount(state) { // 회원정보 불러오기
        return state.account;
    },
};

2. Vuex Module

ex) store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import appointment from '@/store/modules/appointment';
import bookmark from '@/store/modules/bookmark.js';
import map from '@/store/modules/map';
import place from '@/store/modules/place';
import review from '@/store/modules/review';
import snackbar from '@/store/modules/snackbar';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    appointment,
    bookmark,
    map,
    place,
    review,
    snackbar,
  },
});

ex) store/modules/bookmark.js

export default {
  state: {
    bookmark: false,
  },
    
  getters: {
    bookmark(state) {
      return state.bookmark;
    },
  },
    
  mutations: {
    trueBookmark(state) {
      state.bookmark = true;
    },
    falseBookmark(state) {
      state.bookmark = false;
    },
  },
    
  actions: {
    visibleBookmark({ commit }) {
      commit('trueBookmark');
    },
    invisibleBookmark({ commit }) {
      commit('falseBookmark');
    },
  },
    
};

rootState 는 actions 와 getters 에서만 사용가능

vuex 를 모듈형으로 개발할 때, 기본적으로 state 변수 값은 동일 모듈에 있는 state만 참조하게 됩니다.

만약 내가 최상위에 있는 state 변수나 다른 모듈의 변수 값을 활용하기 위해서는 rootState 를 활용해야 한다 하지만 이 rootState는 actions과 getters의 인자로만 사용될 수 있습니다.

만약 mutations에서 사용하기를 원한다면 actions 에서 받아서 mutations쪽으로 commit해서 활용해야 합니다.

Mutations와 Actions의 사용가능 인자

// 방법1 - 제일 많이 쓰임
mutationA(state, payload) {
    
}

// 방법2 - 이렇게도 가능
mutationA(state, {data1, data2}) {
    
}
// 방법1 - 제일 많이 쓰임
actionsA({ rootState, state, commit, dispatch }, payload) {
    
}

3. 접근방법

Components에서 store에 있는 state, mutations, actions, getters 에 접근하는 방법은 아래와 같다

  1. this.$store.state.items

  2. mapState 활용방법

computed: {
    ...mapState({
        items: state => state.items,
    }),
}
  1. this.$store.commit('경로명/함수명')
  2. mapMutaions 활용방법
methods: { // methods 영역에서 호출해야 함
    ...mapMutations({
        add: 'item/increment' // this.add() 를 this.$store.commit('item/increment') 에 매핑
    })
}
  1. this.$store.dispatch['경로명/함수명']
  2. mapActions 활용방법
methods: { // methods 영역에서 호출해야 함
    ...mapActions({
        add: 'item/increment' // this.add()를 this.$store.dispatch('item/increment')
    })
}
  1. this.$store.getters['경로명/함수명']
  2. mapGetters 활용방법
computed: {
    ...mapGetters({
        doneCount: 'item/doneTodosCount'
    })
}

4. 모듈로 구성된 vuex에서 상위모듈 dispatch, commit 실행

모듈로 구성할 경우 하위 모듈에서 형제 또는 부모 모듈의 state에 접근하기 위해서는 rootState를 사용하면 됩니다. 그러면 형제 또는 부모 모듈의 Mutations나 Actions를 실행시킬 경우는 어떻게 해야 하느냐!!! 세번쨰 인자에 { root: true }를 지정해 주면 됩니다

dispatch("path1/actionA", payload, { root: true });