Vue - Vuex(Store)

김영준·2023년 8월 7일
0

TIL

목록 보기
72/91
post-thumbnail

상하위 관계 컴포넌트가 아닌 형제 컴포넌트에서 데이터를 주고받을 때는 어떤 방식으로 해야할까?

Store 개념을 활용하여 State를 관리할 수 있다.

store

  • state 관리를 store 파일로 분류해서 중앙 집중화, 내부 로직들을 분류
  • 예측 가능한 방식으로 state를 변경
  • 추후 관리가 용이

store 폴더에 index.js 파일 생성

import { reactive } from "vue";

// state 초기화
// reactive: 객체 데이터를 반응형으로 만들어주는 Proxy 인스턴스를 반환
export const state = reactive({
    msg: "Hello Vue?!",
    count: 1,
});

// 계산된 데이터
export const getters = {
    reversedMsg(){
        return state.msg.split("").reverse().join("");
    }
};

// state 변경 로직들
export const mutations = {
    increaseCount() {
        state.count += 1;
    },
    decreaseCount(){
        state.count -= 1;
    },
    updateMsg(newMsg){
        state.msg = newMsg;
    }
};

// state 변경 관리 외 기타 로직들
export const actions = {
    async fetchTodo(){
        const todo = await fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then(res => res.json());
        console.log(todo);
        mutations.updateMsg(todo.title); // state 변경은 mutations를 통해서만 가능하게 작성
    }
};

State 사용


Vuex

위 과정을 좀 더 편리하게 사용할 수 있는 상태 관리 라이브러리
state를 외부에서 수정하지 못하게 방지시켜준다.


Vuex 사용하기

vuex 패키지 설치

npm i vuex

src/store/index.js에 아래 코드 작성

import { createStore } from "vuex";

export default createStore({
    // data는 함수로 생성
    state(){
        return {
            msg: "Hello Vue?!",
            count: 1
        };
    },
    getters:{
        // 첫번째 인수로 state를 받음 createStore의 state를 참조
        reversedMsg(state){
            return state.msg.split("").reverse().join("");
        }
    },
    mutations: {
        // 첫번째 인수로 state를 받음 createStore의 state를 참조
        increaseCount(state){
            state.count += 1;
        },
        updateMsg(state, newMsg){
            state.msg = newMsg;
        }
    },
    actions: {
        // 첫번째 인수로 context를 받음 => state, getters, commit, dispatch 존재
        async fetchTodo({ commit }){
            const todo = await fetch("https://jsonplaceholder.typicode.com/todos/1")
            .then(res => res.json());
            console.log(todo);
            commit("updateMsg", todo.title); // mutations의 함수 실행
        }
    }
});

main.js에 플러그인 등록

import { createApp } from "vue";
import App from "~/App";
import store from "~/store";

const app = createApp(App);
app.use(store); // vuex 플러그인 등록. 모든 컴포넌트에서 $store 사용 가능
app.mount("#app");

사용

  • state와 getters는 computed 내부에 작성
  • mutations와 actions는 methods 내부에 작성
  • mutations의 함수를 사용할 때는 commit
  • actions의 함수를 사용할 때는 dispatch

모듈화

index.js에서 하나의 store로 모든 컴포넌트의 state를 관리하는 것은 너무 방대하다.

따라서 store를 기능에 맞게 모듈화 해서 사용할 수 있다.

모듈로 나눌 store 파일을 생성하고 namespaced의 값을 true로 지정해야 한다.

접근 방법
state: this.$store.state.NS.S
getters: this.$store.getters["NS/G"]
mutations: this.$store.commit("NS/M")
actions: this.$store.dispatch("NS/A")


모듈화 전


모듈화 후


매핑

store에서 가져와야 될 내용이 많을 경우 매핑을 통해서 한 번에 가져올 수 있다.

...map함수("네임스페이스 이름", [속성])

매핑 전


매핑 후

profile
꾸준히 성장하는 개발자 블로그

0개의 댓글