[Vue+] Vuex

INO·2022년 8월 7일
0

Vue

목록 보기
24/25
post-thumbnail

상태관리

상태 관리는 모던 프레임워크들 모두 사용하는 개발 패턴입니다. Vue에서는 Vuex라는 상태 관리 패턴을 사용합니다.

상태 관리가 필요한 이유는 컴포넌트의 숫자가 많아졌을 때 컴포넌트 간의 데이터 전달이나 관리가 어렵기 때문에 데이터 전달을 더 명시적이고 효율적으로 하기 위해 Vuex를 사용합니다.

Vuex

Vuex는 뷰의 상태 관리 패턴이자 라이브러리입니다.

Vuex는 화면(Viex) -> 이벤트 발생(Actions) -> 데이터 변경(State)

설치

npm install vuex

등록

/* store.js */
import {createStore} from "vuex";

export default createStore({
    state: {},
    mutations: {},
    actions: {},
    modules: {}
});
/* main.js */
import store from "@/assets/script/store";
app.use(store);

위와 같은 과정을 거치게 되면 Vuex를 사용할 수 있게 됩니다

State

State(상태)는 여러 컴포넌트 간에 공유되는 데이터를 의미합니다.

선언
export default createStore({
	state: {
    	isLoading: false
    }
});

isLoading이라는 state이며 로딩 상태인지 아닌지를 나타내는 state입니다.

Vuex의 state 접근

우리가 정의한 state에 접근하기 위해서는 $state에 접근해야 합니다.

<p>{{this.$store.state.isLoading}}</p>
getters

Vuex에서 computed 속성과 매칭되는 기술 요소가 있습니다. 바로 getter입니다. state 값이 변경되었을 때 변화에 따른 차이를 자동으로 반영하여 값을 계산해줍니다.

export default createStore({
	state: {
    	isLoading: false
    },
    getters: {
    	showLoading(state) {
        	return state.isLoading = true;
        },
        hideLoading() {
        	return state.isLoading = false;
        }
    }
})
getters 접근
<p>{{this.$store.getters.showLoading}}</p>

mutations

mutations은 Vuex에서 상태 값을 변경하는 유일한 방법입니다. state를 변경할 때는 항상 뮤테이션을 변경합니다.

mutations 선언

export default createStore({
	state: {
    	isLoading: false
    },
    mutations: {
    	showLoading(state) {
        	state.isLoading = true;
        },
        hideLoadgin(state) {
        	state.isLoading = false;
        }
    }
})

mutations를 사용할 때는 commit API를 사용해야 합니다.

new Vue({
	methods: {
    	getData() {
        	this.$store.commit("showLoading");
        }
    }
})

getters에서도 값이 수정이 되지만 Vuex에서 지정한 mutations에서 값을 수정하는 것이 좀더 좋아보인다. 왜 mutations를 사용한지는 추후에 공부를 좀 더 한 다음에 더 적어봐야겠다.

profile
🎢

0개의 댓글