-
vue3 에서 vuex4 시작하기 - module 관리프론트엔드/Vuejs 2021. 6. 14. 17:03
vue3 를 사용하게 되면 vuex4 를 사용하여 store 를 관리 할 수 있다.
vuex 4 설치
npm install --save vuex@4.0.1
store 작성
vuex 의 store를 module 형식으로 구성
|-- store
| |-- index.js
| |-- mutation-types.js
| |-- modules
| |-- person.js
- mutation-types.js : 뮤테이션 타입 정의를 담당
- modules : vuex 에서 각 모듈들을 담아두는 폴더
- index.js : vuex 의 store 를 정의
다음과 같은 구조로 해야 소스관리가 편하다.
mutation-types.js 작성
export const PERSON = { SET_NAME: 'SET_NAME', // 이름을 변경하는 타입 정의 };
person.js 모듈 작성
방법1
import { PERSON } from '../mutation-types'; const state = { name: '', age: 0, } const getters = { personInfo: (state) => { return `이름 : ${state.name}, 나이 : ${state.age}`; } } const actions = { changeName({ commit }, value){ commit(PERSON.SET_NAME, value); }, } const mutations = { [PERSON.SET_NAME](state, value) { state.name = value; } } export default { namespaced: true, state, getters, actions, mutations }
방법2
import { PERSON } from '../mutation-types'; export const person = { state: () => ({ name: '', age: 0, }), mutations: { [PERSON.SET_NAME](state, value) { state.name = value; } }, getters: { personInfo(state) { return `이름 : ${state.name}, 나이 : ${state.age}`; } }, actions: { changeName({ commit }, value){ commit(PERSON.SET_NAME, value); }, } };
store 의 모듈들은 state, mutations, getters, actions 라는 속성으로 이루어져야 store 를 관리 하기 수월하다.
참고 : namespace
store 를 모듈화 할떄는 어떤 스토어에서 어떤 모듈을 사용했는지 헷갈리므려 namespaced 를 꼭 사용해서
person/personInfo 등등으로 이름으로 호출 가능
namespace 를 사용시
state는 기존대로 state.moduleName.stateName으로 호출
getters는 computed(() => store.getters["moduleName/getterName"])으로 호출
mutation은 store.commit("moduleName/mutationName", params)으로 호출
action은 store.dispatch("moduleName/actionName", params)으로 호출
index.js (스토어 선언 작성)
스토어를 선언하는 방법은 이전과 달리 createStore 를 통해 생성한다
import { createStore } from 'vuex'; import person from './modules/person'; export default createStore({ modules: {person}, })
여러개 모듈로 할 경우 아래와 같이 mudules 에 추가하면 된다.
import { createStore } from "vuex"; import { Counter } from "@/store/modules/Counter"; import { moduleA } from "@/store/modules/moduleA"; export default createStore({ modules: { Counter, moduleA } });
store 연결하기 (main.js 작성)
위의 작성된 코드를 main.js 에서 연결을 해야 한다.
스토어의 연결을 위해 위에서 작성한 스토어 선언 파일을 불러와서 .use() 를통해 사용하도록 해주면 vuex 설정이 완료된다.
import { createApp } from "vue"; import App from "./App.vue"; import store from "./store"; createApp(App) .use(store) .mount("#app");
useStore
vuex 4 에서 새로나온 useStore 는 스토어를 사용하는 새로운 방법
const store = useStore(); // 스토어 호출 const name = computed(() => store.state.person.name); // state 정보 가져오기 const personInfo = computed(() => store.getters['person/personInfo']); // getters 가져오기 const changeName = e => store.dispatch('person/changeName', e.target.value); // 액션함수
useStore를 사용한 예제 코드 작성
<template> <div id="app"> <h2>{{name}}</h2> <p>{{personInfo}}</p> <input type="text" :value="name" @input="changeName" placeholder="이름을 작성해 주세요."/> </div> </template> <script> import {computed} from 'vue'; import {useStore} from 'vuex'; function usePerson() { const store = useStore(); const name = computed(() => store.state.person.name); const personInfo = computed(() => store.getters['person/personInfo']); const changeName = e => store.dispatch('person/changeName', e.target.value); return { name, personInfo, changeName } } export default { name: 'App', setup() { return { ...usePerson() } }, } </script>
참고문헌
> https://kyounghwan01.github.io/blog/Vue/vue3/composition-api-vuex/#vuex-%E1%84%89%E1%85%A6%E1%84%90%E1%85%B5%E1%86%BC-%E1%84%86%E1%85%B5%E1%86%BE-store-module-1%E1%84%80%E1%85%A2%E1%84%85%E1%85%A9-%E1%84%89%E1%85%B5%E1%86%AF%E1%84%92%E1%85%A2%E1%86%BC [vue3에서 vuex 사용법 한글설명 자세함]
> https://next.vuex.vuejs.org/guide/migrating-to-4-0-from-3-x.html [공식문서]
반응형'프론트엔드 > Vuejs' 카테고리의 다른 글