Vuejs
[Vuejs] vuex
yujeong kang
2020. 11. 23. 03:34
vuex
- vuejs application에 대한 상태관리패턴 + 라이브러리
- application의 모든 컴포넌트들의 중앙 저장소 역할 ( 데이터 관리 )
- vuex 저장소
- state : 단일 상태 트리 사용. application마다 하나의 저장소 관리한다. ( data와 동일 )
- Getters : Vue Instance 의 Computed 와 같은 역할. State 를 기반으로 계산 ( computed )
- Mutations : State의 상태를 변경하는 유일한 방법 ( methods )
- Actions : 상태를 변이 시키는 대신 액션으로 변이에 대한 커밋 처리 ( 비동기 methods )
- state 접근 방식 : this.$store.state.data_name
- getters 사용 : this.$store.getters.countMsg
<template>
<div>
<h2>{{ total }}</h2>
<h2>{{ countMsg }}</h2>
<!-- mapGetter()
<h2>{{ $store.getters.msg1 }}</h2>
<h2>{{ $store.getters.msg2 }}</h2>
<h2>{{ $store.getters.msg3 }}</h2>
-->
<h2>{{ msg1 }}</h2>
<h2>{{ msg2 }}</h2>
<h2>{{ msg3 }}</h2>
</div>
</template>
<script>
import { mapGetters } from "vuex";
console.dir(mapGetters(["countMsg", "msg1", "msg2", "msg3"]));
export default {
computed: {
...mapGetters(["countMsg", "msg1", "msg2", "msg3"]), // spread operator: 객체 속성 넣기~
total() {
return this.$store.state.count;
},
/*
countMsg() {
return this.$store.getters.countMsg;
},
*/
},
};
</script>
getters 는 mapGetters 를 사용해 더 편하게 사용할 수 있다.
- mutations
- state 값 변경하기 위해 사용
- store.commit('정의된 이름')으로 호출
- Actions
- 비동기 작업 결과를 적용하려고 할 때 사용
- Mutations는 상태 관리를 위해 동기적으로 처리하고 비동기적인 처리는 Actions가 담당한다.
- Actions는 비동기 로직 처리가 종료되면 Mutations를 호출한다.