vue.js/vue.js 2

43. vuex 기술 요소 (state, getters, mutations, actions)

DEV-Front 2022. 8. 2. 00:20
반응형

vuex 기술 요소

- state : 여러 컴포넌트에 공유되는 데이터 data

- getters : 연산된 state 값을 접근하는 속성 computed

- mutations : state 값을 변경하는 이벤트 로직, 메서드 methods

- actions : 비동기 처리 로직을 선언하는 메서드 aysnc methods


state 란?

여러 컴포넌트 간에 공유할 데이터 - 상태

// vue
data : {
	message: "hello vue.js!"
}


// vuex
state: {
	message: "hello vue.js!"
}
<!-- vue -->
<p> {{ message }} </p>

<!-- vuex -->
<p> {{ this.$store.state.message }} </p>

getters란?

- state 값을 접근하는 속성이자 computed() 처럼 미리 연산된 값을 접근하는 속성

// store.js
state:{
	num : 10
},
getters: {
	getNumber(state){
    	return state.num
    },
    doubleNumber(state){
    	return state.num * 2;
    }
}
<p>{{ this.$store.getters.getNumber }}</p>
<p>{{ this.$store.getters.doubelNumber }}</p>

mutations 란?

- state의 값을 변경할 수 있는 유일한 방법이자 메서드

- 뮤테이션은 commit() 으로 동작시킨다.

// store.js
state: {num:10},
mutations:{
	printNumbers(state){
    	return state.num
    },
    sumNumbers(state, anotherNum){
    	return state.num + anotherNum;
    }
}

// App.vue
this.$store.commit('printNumbers');
this.$store.commit('sumNumbers', 20);

- 뮤테이션은 첫번째 속성으로 항상 state를 가져온다. 그래서 조절할수 있다.

 

mutations의 commit() 형식

- state를 변경하기 위해 mutations를 동작시킬 때 인자 (payload)를 전달 할 수 있음

// store.js

state:{storeNum:10},
mutations:{
	modifyState(state, payload){
    	console.log(payload.str);
        return state.storeNum += payload.num;
    }
}

// App.vue
this.$store.commit('modifyState',{
 str : 'passed from payload',
 num : 20
})

 

state 는 왜 직접 변경하지 않고 mutations로 변경할까?

- 여러개의 컴포넌트에서 아래와 같이 state 값을 변경하는 경우 어느 컴포넌트에서 해당 state를 변경했는지 추적하기가 어렵다

methods:{
	increaseCounter() { this.$store.state.countre++;}
}

- 특정 시점에 어떤 컴포넌트가 state를 접근하여 변경한 건지 확인하기 어렵기 때문

- 따라서, 뷰의 반응성을 거스르지 않게 명시적으로 상태 변화를 수행. 반응성, 디버깅, 테스팅 혜택.


actions 란?

- 비동기 처리 로직을 선언하는 메서드. 비동기 로직을 담당하는 mutations

- 데이터 요청, Promise, ES6 asyns과 같은 비동기 처리는 모두 actions에 선언

// store.js
state:{
	num : 10
},
mutations:{
	dobleNumber(state){
    	state.num * 2;
    }
},
actions:{
	delayDoubleNumber(context){ // context로 store의 메서드와 속성 접근
    	context.commit('doubleNumber');
    }
}

// App.vue
this.$store.dispatch('delayDoubleNumber');

actions 비동기 코드 예제 1

// store.js
mutations:{
	addCounter(state){
    	state.counter++
    },
},
actions: {
	delayedAddCounter(context){
    	setTimeout(() => context.commit('addCounter'),2000);
    }
}


// App.vue
methods:{
	incrementCounter(){
    	this.$store.dispatch('delayedAddCounter');
    }
}

actions 비동기 코드 예제 2

// store.js

mutations: {
	setData(stare, fetchedData){
    	state.product = fetchedData;
    }
},
actions: {
	fetchProductData(context){
    	return axios.get('https://domain.com/products/1')
        	.then(response => context.commit('setData', response));
    }
}

// App.vue
methods:{
	getProduct(){
    	this.$store.dispatch('fetchProductData');
    }
}

https://joshua1988.github.io/web-development/javascript/promise-for-beginners/

 

 

자바스크립트 Promise 쉽게 이해하기

(중급) 자바스크립트 입문자를 위한 Promise 설명. 쉽게 알아보는 자바스크립트 Promise 개념, 사용법, 예제 코드. 예제로 알아보는 then(), catch() 활용법

joshua1988.github.io

https://joshua1988.github.io/web-development/javascript/javascript-asynchronous-operation/

 

자바스크립트 비동기 처리와 콜백 함수

(중급) 중급 자바스크립트 개발자가 되기 위한 자바스크립트 비동기 처리와 콜백 함수 이해하기. 콜백 지옥과 해결 방법 등

joshua1988.github.io



 

반응형