티스토리 뷰

반응형


Vuex - 주요기술요소 정리

  • state : 여러 컴포넌트에 공유되는 데이터의 상태 data
  • getters : 연산된 state 값을 접근하는 속성 computed
  • mutations : state 값을 변경하는 이벤트 로직 - methods
  • actions : 비동기 처리 로직을 선언하는 메서드 - aysnc methods
    • ex) API Call할 경우 기다렸다가 값을 받을 사용


1. state와 getters 소개

가. state 란?

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

예제1 - (Vue vs Vuex)

변수 선언하기

// Vue data: { message: 'Hello Vue.js!' } // Vuex state: { message: 'Hello Vuex.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.doubleNumber }}</p>


2. state 속성 적용

가. 예제

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        headerText: 'TODO it!'
    }
});


main.js

import { store } from './store/store'

new Vue({
	...
  store,
	...
});


Header.vue

<template>
    <header>
        <h1>{{ this.$store.state.headerText }}</h1>
    </header>
</template>


결과
  • 그림과 같이 Vuex 에서 $store state에 접근한 Text가 표시됨을 알 수 있다.

mutations와 commit() 형식 소개

가. mutations란?

  • state의 값을 변경할 수 있는 유일할 방법이자 methods
  • 뮤테이션은 commit()으로 동작시킨다.

store.js

state: {
	num: 10
},

mutations: {
	printNumbers(state) {
		return state.num;
	},
	sumNumbers(state, anotherNum) {
		return state.num * 2;
	}
}


App.vue

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

나. commit() 형식

store.js

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

App.vue

this.$store.commit('modifyState', {
	str: 'pass str',
	num: 20
});

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

  • 어느 컴포넌트에서 해당 state를 변경했는지 추적하기 어렵다.

4. actions란?

  • mutations에게 신호를 보내는 역할
  • 비동기 처리 로직은 선언하는 메서드, 비동기 로직을 담당하는 mutations
  • 데이터 요청, Promise, ES6 async과 같은 비동기 처리는 모두 actions에 선언

가. 예제1

store.js

state: {
	num: 10
},
mutations: {
	doubleNumber(state) {
		state.num * 2;
	}
},
actions: {
	// context로 store의 메서드와 속성 접근
	delayDoubleNumber(context) {
		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(state, fetchedData) {
		state.product = fetchedData;
	},
},
actions: {
	fetchProductData(context) {
		return axios.get('https://domain.com/product/1')
			.then(response => context.commit('setData', response));
	}
}

App.vue

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




참조











반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함