상태 관리를 위한 패턴이자 라이브러리이고, 중앙 집중식 저장소 역할을 담당
한곳에서 관리
하는 패턴데이터를 store라는 파일을 통해 관리
하고 프로젝트 전체에 걸쳐 활용
할 수 있게 해주는 방법프로젝트 전체에서 사용되는 변수를 store의 state에 저장하고 사용
하게 됨state
: 컴포넌트 간에 공유할 dataview
: 데이터가 표현될 templateactions
: 사용자의 입력에 따라 반응할 methods아래의 구성요소는 단방향
으로 흐른다.
$ npm install vuex
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
// 모든 컴포넌트에서 공통으로 사용할 변수(data) 정의
},
mutations: {
// state 값을 변경시키는 역할(methods -> 동기적)
},
getters: {
// 컴포넌트의 계산된 속성의 공통 사용 정의(computed)
},
actions: {
// setTimeout()이나 ajax같이 결과를 받아올 타이밍이 예측되지 않는 로직 작성(methods -> 비동기적)
}
})
import { store } from "./store";
new Vue({
render: h => h(App),
store,
}).$mount('#app')
- 프로젝트에서
공통으로 사용할 변수를 정의
- 프로젝트 내의 모든 곳에서 참조 및 사용이 가능
- state에 등록한 counter 속성은 $store.state.counter로 접근할 수 있다.
📝 MainPage.vue
<p>{{ $store.state.counter }}</p>
📝 store.js
export const store = new Vuex.Store({
state: {
counter: 0,
},
});
- 컴포넌트의
계산된 속성의 공통 사용 정의
computed에 등록하여 사용
(함수 형태)- computed의 장점인 캐싱 효과는 단순히 state 값을 반환하는 것이 아니라, getters에 선언된 속성에서 filter(),reverse()등의 추가적인 계산 로직이 들어갈 때 발휘된다.
getters에 있는 전달 인자는 state와 getters
이다.getters는 다른 getter
이다.
📝 MainPage.vue
<p>{{ $store.getters.doubleCounter }}</p>
<!-- return 2 -->
📝 store.js
export const store = new Vuex.Store({
state: {
counter: 1,
},
getters: {
doubleCounter(state) {
return state.counter*2
}
},
});
state 값을 변경시키는 역할 (mutations을 통해서만 state를 변경해야 함)
methods에 등록하여 사용
(함수 형태)동기적 처리
(위의 함수가 실행되고 종료된 후에 아래의 함수가 실행)metations의 전달 인자는 state와 payload
이다.- 기본 인자는 state만 사용할 수 있고, commit로 넘어온 인자는 payload만 있다.
- payload는 여러 개를 묶는 객체 형태로 전달될 수 있다.(*payload: 전송되는 data)
- 또한 바로 중괄호로 묶어서 객체 형태로도 전달받을 수 있다.
this.$store.mutations.addCounter; // 이런식의 호출이 불가능하고
this.$store.commit("addCounter"); //commit을 이용하여 mutations 이벤트를 호출
📝 MainPage.vue
<template>
<div id="app">
<!-- 숫자 1씩 증가 -->
<p>{{ $store.state.counter }}</p>
<button @click="$store.commit('addCounter')">+</button>
<!-- 숫자 8로 증가 -->
<p>{{ $store.state.payloadCheckNum }}</p>
<button @click="changeNum"> button </button>
</div>
</template>
<script>
export default {
methods: {
changeNum() {
this.$store.commit("changeNum", {
value: 8
})
}
}
}
</script>
📝 store.js
export const store = new Vuex.Store({
state: {
counter: 1,
payloadCheckNum: 1
},
mutations: {
// state 값을 변경시키는 역할(methods -> 동기적)
addCounter(state) {
state.counter++;
},
changeNum(state, payload) {
state.payloadCheckNum = payload.value
}
},
});
비동기적 처리
(순서에 상관없이 먼저 종료된 함수의 피드백을 받아 후속 처리)- → setTimeout()이나 ajax같이 결과를 받아올 타이밍이 예측되지 않은 로직 작성
- state 관리에 주안점
methods에 등록하여 사용
(함수 형태)- 비동기적 처리이기 때문에 보통 콜백 함수로 작성
actions를 호출할 때는 dispatch()를 이용
actions에 전달 인자는 context와 payload
가 있고, 넘기는 방법은 mutations와 유사하다.
📝 MainPage.vue
<template>
<div id="app">
<!-- 숫자 1씩 증가 -->
<p>{{ $store.state.counter }}</p>
<button @click="addCounter">+</button>
<button @click="delayFewMinutes"> button </button>
</div>
</template>
<script>
export default {
methods: {
addCounter() {
this.$store.commit("addCounter")
},
delayFewMinutes() {
this.$store.dispatch("delayFewMinutes")
}
}
}
</script>
📝 store.js
export const store = new Vuex.Store({
state: {
counter: 1,
},
mutations: {
addCounter(state) {
state.counter++;
},
},
actions: {
delayFewMinutes(context) {
return setTimeout(function () {
context.commit("addCounter");
}, 1000);
},
}
});