프로그래밍/Js

vue options API vuex Store modules 사용법

소행성왕자 2023. 4. 13. 14:03

vuex store 사용시 많은 양의 데이터를 하나의 store 파일에서 작업하기엔 벅차 store 모듈로 쪼개는 방법을 알아보고자 합니다.

store 디렉토리 구조

store/modules/Counter.js
     /modules/moduleA.js
     index.js

index.js

import { createStore } from 'vuex'
import { Counter } from './modules/Counter'
import { moduleA } from './modules/moduleA'

export default createStore({
	mudules: { Counter, moduleA },
    //기존 저장소

});

moduleA.js

export const moduleA = {
	namespaced: true,
    state: {
    	Users:[
        	{id:1, name:'라이언'},
            {id:2, name:'어피치'},
            {id:3, name:'네오'},
            {id:4, name:'무지'},
        ],
    },
    getters: {
    	UsersInfo: state=>{
        	return state.Users;
        },
    },
    mutations: {
    	addUsers: (state, payload)=>{
        	state.Users.push(payload);
        },
    },
    actions: {
    	addUsers: ({commit, state}, payload) => {
        	console.log('>>> state');
            console.log(state);
            commit('addUsers', payload);
        }
    },

};

Counter.js

export const Counter = {
	namespaced: true,
    
};

components 에서 사용법

<template>

	<ul>
    	<li v-for="user in $store.getters['moduleA/UsersInfo']">
        	{{ user.name }}
        </li>
    </ul>
    <button @click = "inc()">유저등록</button>

</template>

<script>
import { ref, computed } from 'vue';
import { useStore, mapState } from 'vuex';

export default {
	name:'appRoot',
    components: {W6108S01};
    created() {
    	this.$trData.init(this);
        this.$socketWorker.init(this);
	},
    setup() {
    	const store = useStore();
    },
    mounted() {
    	const Table = (_=>{
        	//자유변수 공간
            return class {
            	constructor() {}
                async load() {}
            };
        })();
    },
    data() {
    	return {
        	loginInfo: {},
            isAfterLogin: false,
        }
    },
    computed: {
    },
    methods: {
    	dd(data, head='') {
        	console.log(`>> ${head}`);
            console.log(data);
        },
        inc() {
        	const aa = { id:5, name:'개발이 취미'};
			// mutations 호출
			this.$store.commit('moduleA/addUsers', aa);
            // action 호출
            this.$store.dispatch('moduleA/addUsers', aa);
        },
    },

}

</script>

 

namespace 를 사용시

state는 기존대로 state.moduleName.stateName으로 호출

getters $store.getters["moduleName/getterName"] 으로 호출

mutation this.$store.commit('moduleA/addUsers', param) 으로 호출

action this.$store.dispatch('moduleA/addUsers', param) 으로 호출

 

참고 : https://any-ting.tistory.com/44

 

[Vue] 공용 저장소 Vuex 설치 및 사용법

- 지난 시간 안녕하세요. 지난 시간에는 Computed와 Watch 그리고 Method에 대해 알아봤습니다. 혹시 놓치고 오신 분들은 아래 링크를 통해 학습하고 오시는 걸 추천드리겠습니다. any-ting.tistory.com/43 [Vu

any-ting.tistory.com

computed 테스 해봤는데 안됨